简体   繁体   中英

Conditional Proc in ruby/rails?

Proc is used in our code for selecting records. Here is an example:

Proc.new { models.where('payment_requestx_payment_requests.paid = ?',  params[:paid_s] == 'true')}

We are looking for a way to run this Proc if a simple condition is met. Otherwise skip the Proc if condition returns false. Something like:

Proc.new { models.where('payment_requestx_payment_requests.paid = ?',  params[:paid_s] == 'true') if params[:condition] == 'true' }

The condition has to be inside the Proc . Is this something doable in ruby/rails?

Maybe using ternary operator could help?

p = Proc.new {condition ? puts('condition is true!') : puts('condition is false!')}
condition = false
p.call
>> condition is false!
condition = true
p.call
>> condition is true!

Recreating the setup you are dealing with(sort of):

p = Proc.new { [{a:1}, {b:2}] }
p.call
 => [{:a=>1}, {:b=>2}] 

with an if statement:

p = Proc.new { [{a:1},{b:2}] if false }
p.call
 => nil 

Active record returns an empty array if no records satisfy the where condition so I would assume that is what you need to supply:

p = Proc.new { false ? [{a:1},{b:2}] : [] }
p.call
 => [] 

Or in your case:

Proc.new { params[:condition] == 'true' ? models.where('payment_requestx_payment_requests.paid = ?',  params[:paid_s] == 'true') : [] }

Caveat Emptor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM