mailgun / mailgun-ruby

Mailgun's Official Ruby Library
Apache License 2.0
468 stars 184 forks source link

Remove `OpenStruct` usage, will warn in Ruby 3.4, raise in Ruby 3.5 #321

Closed Earlopain closed 1 month ago

Earlopain commented 7 months ago

Ruby 3.4 will issue a warning for this, and Ruby 3.5 will raise. Also see https://bugs.ruby-lang.org/issues/20309, https://github.com/ruby/ruby/pull/10428

There is a single place here that will need adjusting: https://github.com/mailgun/mailgun-ruby/blob/1a2d2dcf253c2265267d261595416daa879a6342/lib/mailgun/response.rb#L15-L19

The other places are test only and can be fixed simply by adding it to the Gemfile (or alternativly just return a hash from response_generator and use the from_hash method, seems like that should work). I suggest replacing the one usage with the following (untested, should be fine):

ResponseHash = Struct.new(:body, :code)

def self.from_hash(h)
  # Create a "fake" response object with the data passed from h
  self.new ResponseHash.new(h[:body] , h[:code])
end
frederikspang commented 5 months ago

Furthermore, OpenStruct usage is generally discouraged, due to invalidating the global method cache in Ruby.

From RuboCop documentation:

Instantiation of an OpenStruct invalidates Ruby global method cache as it causes dynamic method definition during program runtime.

Earlopain commented 1 month ago

Ruby 3.3.5 now warns about this.

irb(main):001> require "mailgun" /home/user/Documents/mailgun-ruby/lib/mailgun.rb:8: warning: ostruct was loaded from the standard library, but will no longer be part of the default gems starting from Ruby 3.5.0. You can add ostruct to your Gemfile or gemspec to silence this warning.

322