Assigning session hash to a variable doesn't keep modified hash in session

Hey all,

I basically have some nested hashes stored in the session variable:

def set_code(unit_id, code)

 if session[:code].select {|h| h[unit_id]}.empty?
   session[:code] << { unit_id => {}}
 end

  case code
  when 3,4
    session[:code].detect {|h| h[unit_id]}[unit_id][:code_a] ||= []
    session[:code].detect {|h| h[unit_id]}[unit_id][:code_a] << code
  when 8,9
    session[:code].detect {|h| h[unit_id]}[unit_id][:code_b] ||= []
    session[:code].detect {|h| h[unit_id]}[unit_id][:code_b] << code
  end

end

From the code above, you can see four lines of repetitive code. The
problem is if I did this:

unit_hash = session[:code].detect {|h| h[unit_id]}[unit_id]

case code
when 3,4
unit_hash[:code_a] ||= []
unit_hash[:code_a] << code
when 8,9
unit_hash[:code_b] ||= []
unit_hash[:code_b] << code
end

Then the appended code will not be stored in the session.

Any way to refactor this so I dont have 4 repetitive lines of code?

Thanks for response

On Sun, Oct 9, 2011 at 11:28 PM, John M. [email protected] wrote:

case code
From the code above, you can see four lines of repetitive code. The
unit_hash[:code_b] << code
end

Then the appended code will not be stored in the session.

Any way to refactor this so I dont have 4 repetitive lines of code?

Put the result of repetitive code in a variable. This might do the
same:

def set_code(unit_id, code)
s_code = session[:code]
unit_id_hash = s_code.detect {|h| h[unit_id]}

if unit_id_hash.nil?
unit_id_hash = {}
s_code << {unid_id => unit_id_hash}
end

this lookup could be done via a constant Hash as well

key = case code
when 3,4
:code_a
when 8,9
:code_b
end

unit_id_hash[key] << code if key
end

But frankly, your data structure looks suspicious to me. For example:
why is session[:code] an Array containing of Hashes with only one key
value pair? Why don’t you make it a Hash where indexed by code?

Kind regards

robert

thanks for response

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