Alex
Alex

Reputation: 36111

Where can I use cookies in Ruby on Rails

I'm using controller's initializer to setup stuff that I will need.

def initialize
  super()
  a = cookies[:a] # EXCEPTION

end

However I can't use cookies because it's null, the system hasn't read them from the header yet.

The same problem was with ASP.NET MVC, where I couldn't access the cookies in the constructor, but I could access them in the Initialize() method.

How can I get the cookies in Rails?

Upvotes: 1

Views: 1698

Answers (3)

Jed Schneider
Jed Schneider

Reputation: 14671

Specifically, cookies is a hash and what you are doing is adding a key value pair with the syntax hash[:key] = value to the hash. So adding a key, without assigning a value, will give you a nil value when you ask for it.

irb(main):006:0> cookies = {}
=> {}
irb(main):007:0> cookies[:a] = 'value'
=> "value"
irb(main):008:0> cookies.inspect
=> "{:a=>\"value\"}"
irb(main):010:0> a= cookies[:b]
=> nil
irb(main):011:0> cookies.inspect
=> "{:a=>\"value\"}

Upvotes: 0

Shadwell
Shadwell

Reputation: 34774

If you want to set something up prior to each request you should use a before_filter.

class MyController << ApplicationController
  before_filter :cookie_setup

  def cookie_setup
    a = cookies[:a]
    .. whatever you want to do with 'a'
  end
end

Upvotes: 1

Sebastian Br&#243;zda
Sebastian Br&#243;zda

Reputation: 879

Former I have problems with this too, this should works:

cookies['a'] = 'value'
a = cookies['a']

Upvotes: 0

Related Questions