0

I want to create some DRY code by inputting a variable key in the where clause in AR

if I have the field as :email and val as '[email protected]'

how would I write it in Ruby 2 syntax?

with previous syntax I could write

Model.where(field => val)

which would be Model.where(:email => '[email protected]')

in Ruby 2 the where can be written as Model.where(email: '[email protected]')

but how would I use the field variable in this situation?

4
  • Some thing. something: value is just a syntax sugar for :something => value. Commented Oct 12, 2014 at 17:58
  • when the symbol :something is stored in a variable, var => val is possible, but ruby 2 syntax is not possible Commented Oct 12, 2014 at 19:19
  • Well, yes, it's just a syntactic sugar. When it's stored in a variable you can do only variable => val. But if you specify the symbol directly you can do both symbol: val and :symbol => val. Now, there are now named arguments in functions in Ruby 2 as well (robots.thoughtbot.com/ruby-2-keyword-arguments), but this is not the case. where(:email => "...") is just yet another syntactic sugar on top of where({:email => "..."}). You can drop {} around hash, if it's the last argument. See stackoverflow.com/questions/16576477/…. Commented Oct 13, 2014 at 1:37
  • 1
    so, you should still be able to use the old syntax. It's not the use of Ruby 2 named arguments, it;s just the use of Ruby 1.9 fancy hash syntax: breakthebit.org/post/8453341914/…. I guess, if there is a problem, you can just be more explicit: Model.where({field => val}). Commented Oct 13, 2014 at 1:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.