nil puts "OK" unless contact => nil contact == nil =...">

Rubyの詐欺師またはプロキシクラスとは

このレールの「ポリモーフィズム」の発現はどうですか?
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


このような現象は多くの状況で発生し、プロキシクラスの設計パターンの使用に関連しています。 具体的には、ActionViewの場合、非推奨のメソッドを使用すると発生します。 詳細については、activesupport / lib / active_support / deprecation.rb(プロキシDeprecationProxyクラスおよび子孫の実装)およびactionpack / lib / action_view / renderable_partial.rb(それらの使用)を参照してください。

わかりやすくするために、この状況をモデル化しました。
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


ご覧のとおり、^ __に対してundefを実行しなかったため(DeprecationProxyでも実行しません)、__ id__を使用してこのような詐欺師を計算できます


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


All Articles