Module: MonkeyWrench::Hash
- Included in:
- Hash
- Defined in:
- lib/monkey_wrench/hash.rb
Instance Method Summary collapse
-
#collect_kv ⇒ Object
Takes a block that returns a [key, value] pair and builds a new hash based on those pairs Courtesy of snuxoll.com/post/2009/02/13/ruby-better-hashcollect.
- #collect_kv!(&blk) ⇒ Object
- #escape_keys! ⇒ Object
- #to_mailchimp(index = nil, parent_name = nil) ⇒ Object
Instance Method Details
#collect_kv ⇒ Object
Takes a block that returns a [key, value] pair and builds a new hash based on those pairs Courtesy of snuxoll.com/post/2009/02/13/ruby-better-hashcollect
8 9 10 11 12 13 14 15 |
# File 'lib/monkey_wrench/hash.rb', line 8 def collect_kv result = {} each do |k,v| new_k, new_v = yield k, v result[new_k] = new_v end result end |
#collect_kv!(&blk) ⇒ Object
17 18 19 |
# File 'lib/monkey_wrench/hash.rb', line 17 def collect_kv!(&blk) replace(self.collect_kv(&blk)) end |
#escape_keys! ⇒ Object
21 22 23 |
# File 'lib/monkey_wrench/hash.rb', line 21 def escape_keys! collect_kv!{|k,v| [CGI.escape(k.to_s), v]} end |
#to_mailchimp(index = nil, parent_name = nil) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/monkey_wrench/hash.rb', line 25 def to_mailchimp(index = nil, parent_name = nil) result = self.collect_kv do |k,v| if v.is_a?(Array) && v.first.is_a?(Hash) i = 0 v = v.inject({}) do |acc,hash| acc.merge!(hash.to_mailchimp(i, k)) i += 1 acc end elsif v.is_a?(Hash) if parent_name v = v.collect_kv do |key,val| keyname = CGI.escape("#{parent_name.to_s}[#{key.to_s.upcase}]") [keyname, val.to_s] end else v = { k => v }.to_mailchimp(nil, k) end elsif v.is_a?(Array) results = {} i = 0 v.each do |val| keyname = CGI.escape("#{k}[#{i}]") results[keyname] = val.to_s i += 1 end v = results end k = k.to_s k = "[#{index}][#{k.upcase}]" if index k = [parent_name, k].join if k != parent_name.to_s [CGI.escape(k), v] end if result.detect{|k,v| v.is_a?(Hash)} result.values.first else result end end |