Reputation: 210
I'm having trouble finding a way to convert from a parameter hash or a hash with indifferent access to a hash when the values contain hashes.
I'm having trouble converting from this:
hash_indif = {"1570"=>"{:enabled=>false}",
"1571"=>"{:enabled=>false}",
"1572"=>"{:enabled=>false}",
"1573"=>"{:enabled=>false}",
"1574"=>"{:enabled=>false}",
"1575"=>"{:enabled=>false}",
"1576"=>"{:enabled=>false}",
"1577"=>"{:enabled=>false}",
"1578"=>"{:enabled=>false}"}
To this:
hash_thing = {1570 => {:enabled => false},
1571 => {:enabled => false},
1572 => {:enabled => false},
1573 => {:enabled => false},
1574 => {:enabled => false},
1575 => {:enabled => false},
1576 => {:enabled => false},
1577 => {:enabled => false},
1578 => {:enabled => false}}
I'd like to be able to do with method chaining if at all possible.
Additional Information
This situation resulted from trying to update multiple attributes off the same key.
Haml:
- @a_feature.each do |af|
.form-inline.radio-group
%label= af.feature.name
=radio_button "a_feature", af.id, [enabled: true], {checked: af.enabled, class:'form-control'}
%label Yes
=radio_button "a_feature", af.id, [enabled: false], {checked: !af.enabled, class:'form-control'}
%label No
Parameters:
{"utf8"=>"✓",
"_method"=>"patch",
"a_feature"=>{
"296"=>"{:enabled=>true}",
"344"=>"{:enabled=>false}",
"376"=>"{:enabled=>false}",
"commit"=>"Save",
"agency_id"=>"7"}
Upvotes: 1
Views: 357
Reputation: 1413
Here's a quick workaround without using eval
def to_bool(str)
str == 'true'
end
new_hash = Hash.new
hash_indif.each do |i, j|
inner_hash = Hash.new
match_data = /^{:(enabled)=>(false|true)}$/.match(j)
inner_hash[match_data[1].intern] = to_bool match_data[2]
new_hash[i.to_i] = inner_hash
end
The new_hash variable contains the output you need -
{1570=>{:enabled=>false}, 1571=>{:enabled=>false}, 1572=>{:enabled=>false}, 1573=>{:enabled=>false}, 1574=>{:enabled=>false}, 1575=>{:enabled=>false}, 1576=>{:enabled=>false}, 1577=>{:enabled=>false}, 1578=>{:enabled=>false}}
Upvotes: 1