Fellow Stranger
Fellow Stranger

Reputation: 34013

What does .call do?

I came across this method, where in the end .call is used:

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

But the docs don't really give me the understanding of when/how to use .call.

Upvotes: 4

Views: 9755

Answers (1)

Shiva
Shiva

Reputation: 12514

The purpose of the .call method is to invoke/execute a Proc/Method instance. The example below might make it more clear.

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

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

In the above example, Fixnum 12 has the method + defined.

In the example you posted:

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]] returns a Proc instance and resource is a param/argument to the method call.

For example:

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

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

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

FYI: In ruby you can have an Array as the Key of a Hash object.

Upvotes: 16

Related Questions