.call做什么?

时间:2015-11-01 14:39:10

标签: ruby-on-rails ruby

came across此方法,最后使用.call

def allow?(controller, action, resource = nil)
  allowed = @allow_all || @allowed_actions[[controller.to_s, action.to_s]]
  allowed && (allowed == true || resource && allowed.call(resource))
end

但是the docs并没有让我理解何时/如何使用.call

1 个答案:

答案 0 :(得分:3)

对于不了解.call方法的人 .call是一个调用/执行Proc/Method实例的方法。下面的例子可能会让你更清楚

m = 12.method("+")
# => `method` gets the `+` method defined in `Fixnum` instance
# m.class 
# => Method

m.call(3)    #=> 15
# `3` is passed inside the `+` method as argument 
m.call(20)   #=> 32

在上面的例子中; Fixnum 12已定义方法+

在您发布的示例中

def allow?(controller, action, resource = nil)
  allowed = @allow_all || @allowed_actions[[controller.to_s, action.to_s]]
  allowed && (allowed == true || resource && allowed.call(resource))
end

@allowed_actions[[controller.to_s, action.to_s]]向方法调用返回Proc个实例,resourceparam/argument

例如

hash = {[:controller, :action] => 'value'}
# => {[:controller, :action]=>"value"} 

> hash[[:controller,:value]]
# => nil 

> hash[[:controller,:action]]
# => "value" 

仅供参考:在红宝石中,您可以将Array作为Key对象的Hash