NilClass puts "OK" if contact OK => nil puts "OK" unless c...">
📜 ⬆️ ⬇️

Impostors in Ruby or what is Proxy Class

How do you like this manifestation of "polymorphism" in rails?
contact.class
=> NilClass
puts "OK" if contact
OK
=> nil
puts "OK" unless contact
=> nil
contact == nil
=> true
puts "OK" if contact
OK
=> nil
puts "OK" if nil
=> nil


Such a phenomenon occurs in many situations and is associated with the use of the Proxy Class design pattern. Specifically, in the case of ActionView, it occurs when using the deprecated methods. Read more in activesupport / lib / active_support / deprecation.rb (Implementation of proxy classes of DeprecationProxy and heirs) and in actionpack / lib / action_view / renderable_partial.rb (Their use).

Simulated this situation for clarity:
class ProxyClass
silence_warnings { instance_methods.each { |m| undef_method m unless m =~ /^__/ } }

def initialize(target)
@target = target
end

private
def method_missing(called, *args, &block)
@target.__send__(called, *args, &block)
end
end

:

>> @nil_object1 = nil
=> nil
>> @nil_object2 = ProxyClass.new(@nil_object1)
=> nil
>> @nil_object1.object_id
=> 4
>> @nil_object2.object_id
=> 4
>> @nil_object2.__id__
=> 2198992980
>> @nil_object1.__id__
=> 4


As you can see, since for ^ __, undef was not done (in DeprecationProxy, too, they do not), you can calculate such impostors by __id__

')

Source: https://habr.com/ru/post/97802/


All Articles