views:

25

answers:

3

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?

A: 

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

cookies['a'] = 'value'
a = cookies['a']
Sebastian Brózda
+1  A: 

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
Shadwell
Thanks! That solved the problem.
Alex
A: 

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\"}
Jed Schneider
The cookie is not nil, and I do check them. Thanks anyway.
Alex
I think you misunderstood. the value you are adding to the key in your code is nil. `a= cookies[:a]` you are not assigned a value to the key :a. so when you ask for the value stored in a later in `a` it will be nil. because `cookies[:a]` evaluates to nil. your problem has nothing to do with accessing in the constructor, it has to do with not understanding the syntax of how to add key value pairs to a hash.
Jed Schneider
I'm sorry but you don't understand. The problem IS about accessing the cookies from the initializer because the request object is nil. There's the "a" cookie in the browser, so it is NOT nil.
Alex
my bad please disregard.
Jed Schneider