I would like to parse a hash which I receive from Wufoo Webhook API. I am doing this for multiple forms so I can't hardcode values like: params['Field5']
because I don't know how many fields I have.
>> params.class
=> Hash
>> params
=> {"FieldStructure"=>
"{\"Fields\":[
{\"Title\":\"Company Name\",\"Type\":\"text\",\"ID\":\"Field6\"},
{\"Title\":\"Email\",\"Type\":\"email\",\"ID\":\"Field5\"}
]}",
"Field6"=>"testse",
"Field5"=>"gdsgfdgdf@fd.pl",
"CreatedBy"=>"public",
"DateCreated"=>"2013-04-10 07:38:09",
"EntryId"=>"21"}
Basically, I would like to create an object from hash above with attributes:
company_name: "testse", email: "gdsgfdgdf@fd.pl"
You could:
Example:
params = {"FieldStructure"=>
"{\"Fields\":[{\"Title\":\"Company Name\",\"Instructions\":\"\",\"IsRequired\":\"0\",\"ClassNames\":\"\",\"DefaultVal\":\"\",\"Page\":\"1\",\"Type\":\"text\",\"ID\":\"Field6\"},
{\"Title\":\"Email\",\"Instructions\":\"\",\"IsRequired\":\"0\",\"ClassNames\":\"\",\"DefaultVal\":\"\",\"Page\":\"1\",\"Type\":\"email\",\"ID\":\"Field5\"}]}",
"FormStructure"=>
"{\"Name\":\"TestForm\",\"Description\":\"This is my form. Please fill it out. It's awesome!\",\"RedirectMessage\":\"Great! Thanks for filling out my form!\",\"Url\":\"testform\",\"Email\":null,\"IsPublic\":\"1\",\"Language\":\"english\",\"StartDate\":\"2000-01-01 12:00:00\",\"EndDate\":\"2030-01-01 12:00:00\",\"EntryLimit\":\"0\",\"DateCreated\":\"2013-04-09 06:44:12\",\"DateUpdated\":\"2013-04-10 05:25:55\",\"Hash\":\"z7x3p3\"}",
"Field6"=>"testse",
"Field5"=>"gdsgfdgdf@fd.pl",
"CreatedBy"=>"public",
"DateCreated"=>"2013-04-10 07:38:09",
"EntryId"=>"21",
"IP"=>"46.205.117.55",
"HandshakeKey"=>""}
fields = params['FieldStructure'].scan(/Title\":\"(.+?)\".+?ID\":\"(.+?)\"/)
#=> [["Company Name", "Field6"], ["Email", "Field5"]]
Hash[fields.collect{ |field|
[
field[0].gsub(/\s+/, "_").downcase.to_sym,
params[field[1]]
]
}]
#=> {:company_name=>"testse", :email=>"gdsgfdgdf@fd.pl"}