Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use quotes or colons for session keys in Ruby on Rails?

Currently I have a session variable that returns the same value when I use both session["test"] or session[:test]. Are these two the same? Is it better to use one over the other?

Thanks

like image 308
Goalie Avatar asked Apr 24 '12 23:04

Goalie


People also ask

Why colon is used in Ruby?

Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.

What Does a colon before a variable mean in Ruby?

Learn what a colon before a variable means in Ruby This means that two symbols with the same name always refer to the same object.

What is session in Ruby on Rails?

Rails session is only available in controller or view and can use different storage mechanisms. It is a place to store data from first request that can be read from later requests. Following are some storage mechanism for sessions in Rails: ActionDispatch::Session::CookieStore - Stores everything on the client.


2 Answers

In a standard Ruby Hash they're not the same (string vs symbol)

However, the rails SessionHash subclass calls to_s on the keys before storing them, so all keys are stored as strings (even if you specify a symbol):

class SessionHash < Hash

  def [](key)
    load_for_read!
    super(key.to_s)
  end

  def []=(key, value)
    load_for_write!
    super(key.to_s, value)
  end

That's why session[:test] and session["test"] will return the same value in rails.

like image 129
pjumble Avatar answered Nov 14 '22 22:11

pjumble


No, they aren't precisely the same. They're two ways of accomplishing the same thing.

In general, in Ruby a major use of symbols is as keys. Symbols are :these_things. Hash keys are a typical use for them...

{
  :name => 'Mary',
  :rank => 'Captain'
}

Session keys are also usually symbols.

Using Strings instead won't hurt anything, but symbols are more typical.

like image 41
Ethan Avatar answered Nov 14 '22 21:11

Ethan