Cookies & gsub?

I’m looking to store the current params into a/some cookie(s).

This works:

@params.each_pair do |this_index, this_param|
cookies[this_index] = this_param

Except, I get session-only cookies. This doesn’t work:

@params.each_pair do |this_index, this_param|
cookies[this_index] = {
:value => this_param,
:expires => 30.days.from_now

Specifcally, I get the error:

private method `gsub’ called for [“Sonic”, “0”]:Array

I’m not entirely sure I understand why one of these works, but the other
doesn’t. Can someone point me in the right direction here?

I’ve been poking around with this. I’m starting to think this may be a
minor bug in the cookie module… Here’s what I’ve got now:

I’m converting an older app from PHP to Rails. The users makes a few
choices and I display/filter the data to match their choices. I want
to store their choices in a cookie, so they remain “stuck” the next
time the visitor returns to the site.

The problem: Storing a Hash in the cookie with an expiration gives a
“NoMethodError” – not finding “gsub” on the Hash/Array (?).

More specifically:
The user makes a choice as to which book to search in, the source list
comes from the database, and uses abbreviations to track which source
is selected. I converted this almost straight from PHP:

<% @optional_sources.each do |this_source| -%>
<input type=“checkbox” name=“add_sources[]”
value="<%=this_source.abbrev%>" id="<%=this_source.abbrev%>"<%=
‘checked=“checked”’ if
@cookies[‘add_source’].index(this_source.abbrev) %> /> <>

<% end -%>

This returns a @params array like this:

@params[‘add_sources’] = [ ‘ABBREV1’, ‘ABBREV2’, ‘ABBREV3’ ]

Of course, this isn’t a very “Railsian” approach. So I implemented the
next set of choices (let’s say, choosing a city) using the check_box


    <% cities = %w{ Toronto Chicago } cities.each do |this_city| %>
  • <%= check_box ("cities", this_city) %> <%=this_city%>
  • <% end -%>

Which produces a @params hash like this:

@params[‘cities’][‘Toronto’] = 0
@params[‘cities’][‘Chicago’] = 1

Or, to put it another way, like this:

@params[‘cities’] = { ‘Toronto’ => 0, ‘Chicago’ => 1 }

The problem (at long last):
In the first case (sources), this works fine:

cookies[:sources] = { :value => @params[:add_sources], :expires =>
30.days.from_now }

In the second case (cities), this DOES work:

cookies[:cities] = @params[:cities]

BUT, creates a this-session-only cookie. Trying to set an expiration:

cookies[:sources] = { :value => @params[:cities], :expires =>
30.days.from_now }

… produces the gsub error.

in the rails book it says cookie values can only have string types
you’ll run into the gsub error. Agile Rails page 312

you might want to stringify your hash and store it in the cookie. Then
extracting it, parse it back into your hash object.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs