What Does. Call Do?

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.

3

1 Answer

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.