Ruby on Rails Sunday, March 17, 2019

I want to (in a metaprogramming context) invoke a scope on an ActiveRecord based model. I know the name of the scope, but I don't want to use `send` to do this, because send can be evil. I know that ActiveRecord defines a class method named scope that gathers up these scopes somewhere internally, but I can't figure out where that is, or how you can pick one out of the stack to execute.

What is the best equivalent to this (completely made-up example):

def call_scope(model, scope = 'all')
model.send scope.to_sym
end

The key feature is that we late-evaluate which model and which scope, so it can be used inside an enumerator, and doesn't rely on knowing the exact parties in play.

Would this be a good place for class_eval? (I just tried that, and it works)

def call_scope(model, scope = 'all')
model.class_eval scope.to_s
end

Is there something more Rails-like I could/should use?

Am I wrong about send?

Thanks in advance,

Walter

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/96E23293-FE9C-486D-84B2-935D1203E7BB%40wdstudio.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment