Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash rockets vs 1.9 syntax

Railscast Episode 275 - How I test uses the following code to send password resets to users:

def send_password_reset
  generate_token(:password_reset_token)
  ....
  ... etc
end

def generate_token(column)
  begin
    self[column] = SecureRandom.urlsafe_base64
  end while User.exists?(column => self[column])
end

My question regards the penultimate line of code: end while User.exists?(column => self[column]) which works fine as is, but causes my specs to fail if I swap out the hash-rocket i.e. end while User.exists?(column: self[column])

Failure/Error: user.send_password_reset
   ActiveRecord::StatementInvalid:
   SQLite3::SQLException: no such column: users.column: SELECT  1 FROM "users"  WHERE "users"."column" = 'Y7JJV4VAKBbf77zKFVH7RQ' LIMIT 1

Why is this happening? Are there situations where you must use a hash-rocket, and are there any guidelines regarding this?

like image 312
stephenmurdoch Avatar asked Dec 06 '25 07:12

stephenmurdoch


1 Answers

column in that line of code isn't a symbol, its a variable, so you need to use the hash rocket. column: self[column] would build a hash where the key was the symbol :column, not the value of the variable column, which is what you want.

The new syntax is just a shortcut when using a literal symbol for a key (key: value instead of :key => value). If you are using a variable key the => syntax is still required.

like image 51
Carl Zulauf Avatar answered Dec 08 '25 23:12

Carl Zulauf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!