When do you need the splat operator ("*") in Ruby on Rails?
1. To Split an Array into Separate Arguments
When calling a method, if you have an array and you want to pass its elements as separate arguments to a method, you use the splat operator before the array variable.
OAuth::Token.authenticate(
request,
*Doorkeeper.config.access_token_methods,
)
Here, Doorkeeper.config.access_token_methods
returns an array of methods (e.g., [:from_bearer_authorization, :from_access_token_param]). The splat operator (*) is used to pass the elements of this array as separate arguments to the authenticate method.
So, if Doorkeeper.config.access_token_methods returns [:from_bearer_authorization, :from_access_token_param], the call is effectively the same as:
OAuth::Token.authenticate(request, :from_bearer_authorization, :from_access_token_param)
2. To Accept an Arbitrary Number of Arguments
When defining a method, placing a splat operator before a parameter name allows the method to accept any number of arguments for that parameter. These arguments are then available within the method as an array.
def doorkeeper_authorize!(*scopes)
# scopes is an array of all arguments passed to the method.
end
Here, *scopes
means that doorkeeper_authorize!
can be called with any number of arguments (including zero), and those arguments will be collected into an array called scopes inside the method. For example, calling doorkeeper_authorize!(:public, :admin) would result in scopes being [:public, :admin].