这两项工作
Rails.application.credentials.development
Rails.application.credentials.send(:development)
但是,第一个.test
有效,但(:test)无效。
Rails.application.credentials.test
Rails.application.credentials.send(:test)
:test为什么特别?是什么使它不起作用?我得到
[5] pry(#<Cred>)>Rails.application.credentials.send(:test)
ArgumentError: wrong number of arguments (given 0, expected 2..3)
from (pry):5:in `test'
答案 0 :(得分:2)
test
是在Kernel
模块中定义的私有方法。 Kernel
包含在每个红宝石对象中。
当您调用.send(:test)
时,此方法将被调用,它需要2或3个参数。
它也可以在其他对象上复制:
[15] pry(main)> :a.send(:test)
ArgumentError: wrong number of arguments (given 0, expected 2..3)
from (pry):23:in `test'
[16] pry(main)> 1.send(:test)
ArgumentError: wrong number of arguments (given 0, expected 2..3)
from (pry):24:in `test'
编辑
我不确定credentials
是什么对象,所以不能肯定地说是这样,但是当您定义method_missing
时,它是在直接调用私有方法之前调用的,而不是与{ {1}},请参见下文:
send
EDIT2:
通常比class B
def method_missing(*args)
puts args
end
end
pry> B.new.send(:test)
ArgumentError: wrong number of arguments (given 0, expected 2..3)
from (pry):32:in `test'
pry> B.new.test
test
=> nil
#public_send
更安全。它不会让您调用私有方法,而且还会被#send
捕获:
#method_missing