Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a scope with optional arguments?

Tags:

Is it possible to write a scope with optional arguments so that i can call the scope with and without arguments?

Something like:

scope :with_optional_args,  lambda { |arg|
  where("table.name = ?", arg)
}

Model.with_optional_args('foo')
Model.with_optional_args

I can check in the lambda block if an arg is given (like described by Unixmonkey) but on calling the scope without an argument i got an ArgumentError: wrong number of arguments (0 for 1)

like image 652
tonymarschall Avatar asked Apr 26 '12 17:04

tonymarschall


People also ask

How do you pass an optional argument in Python?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.

What is optional argument?

Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

What is optional argument in Python?

In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified.

What is optional arguments in VB?

Optional parameters are indicated by the Optional keyword in the procedure definition. The following rules apply: Every optional parameter in the procedure definition must specify a default value. The default value for an optional parameter must be a constant expression.


3 Answers

Ruby 1.9 extended blocks to have the same features as methods do (default values are among them):

scope :cheap, lambda{|max_price=20.0| where("price < ?", max_price)}

Call:

Model.cheap
Model.cheap(15)
like image 195
jdoe Avatar answered Nov 09 '22 02:11

jdoe


Yes. Just use a * like you would in a method.

scope :print_args, lambda {|*args|
    puts args
}
like image 31
Mark Bolusmjak Avatar answered Nov 09 '22 00:11

Mark Bolusmjak


I used scope :name, ->(arg1, arg2 = value) { ... } a few weeks ago, it worked well, if my memory's correct. To use with ruby 1.9+

like image 30
ksol Avatar answered Nov 09 '22 00:11

ksol