Search code examples
ruby-on-railsrubyruby-on-rails-2

Ruby programming - avoid code duplication when named scopes are used


I have multiple named scopes in my model. They have different names but same parameters. Now, when I use these named scopes based on a condition I have to duplicate the entire parameters all the time. Is there anyway to avoid that?

For ex: In my say a Product model:

named_scope :example1, lambda{ |parameter1, parameter2|{
 //some code here//
 }
}

named_scope :example2, lambda{ |parameter1, parameter2|{
 //some code here//
 }
}

named_scope :example3, lambda{ |parameter1, parameter2|{
 //some code here//
 }
}

Now, I want to use these based on condition

if(condition)

Product.example1(param1, param2)

elsif (condition)

Product.example2(param1, param2)

else

Product.example3(param1, param2)

Is there any way to call it like this in ruby:

variable = example1 //I can get the name of named_scope here

Product.variable(param1, param2). //The relevant named_scope should be used.

Solution

  • You can use Object#send do send Product a message (aka call a method).

    Product.send(variable,param1,param2)