views:

26

answers:

1

Hi,

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

+1  A: 

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.

tadman
Great, I didn't notice the scope method doesn't need an empty Hash in Rails 2.3.8 (there is only a warning triggered), this solves my issue, thanks! Btw, thanks for the 'arity' tip!
vincentp