Search code examples
ruby-on-railsrubyactiverecordenumsactivesupport

Why ActiveSupport try() is override when I define a method try with a bang


What a surprise when I defined a method the set my ActiveRecord User attribute currency_code to Turkish lira (TRY).

So in User I defined:

define_method("try!"){ update! currency_code: :try }.

And it apparently defined both try() and try!() with the same block and the result for User.first.try is updating my user instance.

I investigate but I don't understand where the try() (Active support that prevent you call to a method to raise if it's nil) is override and now execute an update.

To be sure I defined the same one for USD

define_method("usd!"){ update! currency_code: :usd } and this one is working the right way. No usd() method defined here.

I'm not looking for a fix but an explication to this magic :)

Thanks


Solution

  • It's because ActiveSupport's try method also uses try! internally, at least in Rails 5.1:

    # File 'lib/active_support/core_ext/object/try.rb', line 5
    
    def try(*a, &b)
      try!(*a, &b) if a.empty? || respond_to?(a.first)
    end