Module: TheBigDB::Helpers
- Defined in:
- lib/thebigdb/helpers.rb
Class Method Summary collapse
- .flatten_params_keys(params) ⇒ Object
-
.serialize_query_params(params, prefix = nil) ⇒ Object
serialize_query_params(“brick and mortar”, animals: [“cat”, “dog”], computers: {cool: true, drives: [“hard”, “flash”]}) => house=brick%20and%20mortar&animals%5B0%5D=cat&animals%5B1%5D=dog&computers%5Bcool%5D=true&computers%5Bdrives%5D%5B0%5D=hard&computers%5Bdrives%5D%5B1%5D=flash which will be read by the server as: => house=brick%20and%20mortar&animals[]=cat&animals=dog&computers=true&computers[]=hard&computers[]=flash.
-
.stringify_keys(hash) ⇒ Object
Inspired by on ActiveSupport’s stringify_keys.
Class Method Details
.flatten_params_keys(params) ⇒ Object
30 31 32 33 34 35 36 37 38 |
# File 'lib/thebigdb/helpers.rb', line 30 def self.flatten_params_keys(params) serialized_params = self.serialize_query_params(params) new_params = {} serialized_params.split("&").each do |assign| key, value = assign.split("=") new_params[URI.decode(key)] = URI.decode(value) end new_params end |
.serialize_query_params(params, prefix = nil) ⇒ Object
serialize_query_params(“brick and mortar”, animals: [“cat”, “dog”], computers: {cool: true, drives: [“hard”, “flash”]})
> house=brick%20and%20mortar&animals%5B0%5D=cat&animals%5B1%5D=dog&computers%5Bcool%5D=true&computers%5Bdrives%5D%5B0%5D=hard&computers%5Bdrives%5D%5B1%5D=flash
which will be read by the server as:
> house=brick%20and%20mortar&animals[]=cat&animals=dog&computers=true&computers[]=hard&computers[]=flash
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/thebigdb/helpers.rb', line 8 def self.serialize_query_params(params, prefix = nil) ret = [] params.each_pair do |key, value| param_key = prefix ? "#{prefix}[#{key}]" : key if value.is_a?(Hash) ret << self.serialize_query_params(value, param_key.to_s) elsif value.is_a?(Array) sub_hash = {} value.each_with_index do |value_item, i| sub_hash[i.to_s] = value_item end ret << self.serialize_query_params(sub_hash, param_key.to_s) else ret << URI.encode_www_form_component(param_key.to_s) + "=" + URI.encode_www_form_component(value.to_s).gsub("+", "%20") end end ret.join("&") end |
.stringify_keys(hash) ⇒ Object
Inspired by on ActiveSupport’s stringify_keys
41 42 43 44 45 46 |
# File 'lib/thebigdb/helpers.rb', line 41 def self.stringify_keys(hash) hash.inject({}) do |, (key, value)| [key.to_s] = value end end |