2

我想解析从 Wufoo Webhook API 收到的哈希。我正在为多种表单执行此操作,因此我无法对值进行硬编码,例如:params['Field5']因为我不知道我有多少字段。

  >> 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"}

基本上,我想从上面的哈希创建一个带有属性的对象:

company_name: "testse", email: "gdsgfdgdf@fd.pl"
4

1 回答 1

1

你可以:

  1. 扫描 FieldStructure 字符串以确定所需字段的 ID。
  2. 然后使用 id 在 params 哈希中找到所需的值

例子:

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"}
于 2013-04-10T20:28:18.847 回答