Magne
Magne

Reputation: 17223

Dynamic scoping in Rails?

Is it possible to do something like this in ruby on rails?

def method(scope: 'all') # so that it would use Model.all by default
  Model.scope
end

method(scope: 'last(10)') # to get it to call Model.last(10)

Update: For clarification, this is not particularly related to the scope class method in Rails. I probably should have avoided using the term "scope" when originally asking, to avoid confusion. Feel free to think about it as model_method instead. Will leave the question as originally stated though, to preserve history as one of the answers addressed it as such.

Upvotes: 0

Views: 976

Answers (2)

Magne
Magne

Reputation: 17223

I found out how, by using ruby's #send and keyword arguments, and using an array to support model scopes with more than just one argument:

def method(scope: 'all', scope_args: []) # so that the method would call Model.all by default
  Model.send(scope, *scope_args)
end

method(scope: 'last', scope_args: [10]) # to get it to call Model.last(10)
method(scope: 'where', scope_args: [attribute: 'something']) # to get the method to call Model.where(attribute: 'something')

Upvotes: 0

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

You can define respective scopes in Model itself, to handle with and without arguments..

scope :scoping, ->(method = 'all') { send(method) }
scope :scoping_with_arg, ->(method = 'limit', arg = 1) { send(method, arg) }

Then,

Model.scoping('first')
Model.scoping_with_arg('last', 10)

Upvotes: 2

Related Questions