Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'scoped' method for Rails 2.X ad Rails 3

I've got a plugin I'm using for websites using Rails 2.X or Rails 3.

In Rails 2.3, I used a lot the 'scoped' method for complex queries :

p = Person.scoped({})
p = p.active
p = p.with_premium_plan if xyz
p
etc.

But I saw that it changed in Rails 3 :

p = Person.scoped
etc.

So is it normal that I have to do something like that in my plugin (to be able to run it in both version of Rails), or can you suggest something nicer?

if Rails.version.split(".")[0] == "3"
  p = Person.scoped
else
  p = Person.scoped({})
end

Thanks! Vince

like image 919
Vincent Peres Avatar asked Jan 21 '23 16:01

Vincent Peres


1 Answers

I'd really stay away from checking the literal version of Rails. You're just setting yourself up for failure when Rails 4 comes out.

If you're curious if a method takes a parameter or not, use this:

p = (Person.method(:scoped).arity == 1) ? Person.scoped({ }) : Person.scoped

The arity method on a class or module returns the number of parameters required, or a negative value if it's a somewhat arbitrary number as is the case when some are optional.

That being said, in Rails 2.3.8 it doesn't seem you need to pass any parameter to scoped anyway.

like image 106
tadman Avatar answered Jan 24 '23 07:01

tadman