How does the method .call() work?

9.3k Views Asked by At

I'm implementing authorization in an app according to this Railscasts episode.

In one of the instance methods, Ryan Bates is using the method .call and I don't understand what exactly it is doing. This is the code for the whole model. And this is the particular method:

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 resource argument is an instance object and the local variable allowed is supposed to be a boolean value.

1

There are 1 best solutions below

0
On BEST ANSWER

call evaluates the proc or method receiver passing its arguments to it.

pr = ->a{a.map(&:upcase)}
pr.call(%w[hello world])
# => ["HELLO", "WORLD"]

m = "hello".method(:concat)
m.call(" world")
# => "hello world"

It is used to call back a piece of code that has been passed around as an object.