Kullanım public_send
dinamik bir yöntem adı anlaması ve diyoruz, henüz hala kapsülleme sorunları istemiyorum istiyorum. Başka bir deyişle
,
public_send
sadece doğrudan hiçbir iş arounds yöntemin çağrıyı simüle edilecek. Kapsülleme ve meta programlama karıştırma için iyidir.
Örnek: Gördüğünüz gibi
What do you want met to say? hi
=> Hi
=> Hi
What do you want met to say? secret
=> Secret leaked, OMG!!!
=> I didn't learn that word yet :\\
, send
özel yöntem ve dolayısıyla güvenlik/kapsülleme sorunu arayacak:
class MagicBox
def say_hi
puts "Hi"
end
def say_bye
puts "Bye"
end
private
def say_secret
puts "Secret leaked, OMG!!!"
end
protected
def method_missing(method_name)
puts "I didn't learn that word yet :\\"
end
end
print "What do you want met to say? "
word = gets.strip
box = MagicBox.new
box.send("say_#{word}") # => says the secret if word=secret
box.public_send("say_#{word}") # => does not say the secret, just pretends that it does not know about it and calls method_missing.
giriş hi
ve secret
şudur
çıkışı oluşur. kamu ise
public_send
Oysa sadece aksi normal bir davranış (geçersiz eğer
method_missing
arayarak ya da bir
NoMethodError
yükselterek) oluşur yöntemini çağırır. send sonra özel yöntemle yanı sıra halkı çağırabilir ne zaman ve niçin public_send kullanmak eğer
Sorum şu? public_send' –
yakut ilk sürümü beri var olan send' AFAIK 'fakat' sıkı kapsülleme tercih edenler tadı karşılamak için oldukça geç tanıtıldı. – Aetherus
Kamu yöntemlerini çağırmak istediğinizde ve internals ile uğraşmaya çalışmadığınızda 'public_send' işlevini kullanın. Bu şekilde amacınızı, kodunuzun gelecekteki okuyucularına iletirsiniz. –