"sim"} @properties.try(:filtros_has" /> "sim"} @properties.try(:filtros_has" /> "sim"} @properties.try(:filtros_has"/>

Rails .try returning nil when it shouldn't

437 views Asked by At

Can someone explain the following behavior? They both should return the same.

@properties.filtros_hash
=> {"casa"=>"sim"}

@properties.try(:filtros_hash)
=> nil
1

There are 1 answers

0
sandre89 On BEST ANSWER

@properties, in my case, was an instance of a SimpleDelegator. Something like this:

class PropertiesDecorator < SimpleDelegator

    def filtros_hash
        {some_hash: 'hash'}
    end

end

@properties = PropertiesDecorator.new(@properties)

Having that in mind, and reading Rails's documentation about .try, I found out this:

Please also note that try is defined on Object. Therefore, it won't work with instances of classes that do not have Object among their ancestors, like direct subclasses of BasicObject. For example, using try with SimpleDelegator will delegate try to the target instead of calling it on the delegator itself.

So, that explains this highly unexpected behavior, since even tough PropertiesDecorator have a filtros_hash instance method, by using .try the filtros_hash is being delegated to @properties (ActiveRecord) where there is no such method.