Module: FatZebra::Util
- Defined in:
- lib/fat_zebra/util.rb
Constant Summary collapse
- DATE_FORMAT =
'%Y/%m/%d'.freeze
Class Method Summary collapse
-
.compact(hash) ⇒ Hash
Remove nil value from hash.
-
.encode_parameters(params) ⇒ Object
Encodes a hash of parameters in a way that’s suitable for use as query parameters in a URI or as form parameters in a request body.
-
.format_dates_in_hash(hash) ⇒ Hash
Format Date attribute in the params.
- .hash_except(hash, *keys) ⇒ Object
-
.underscore(string) ⇒ Object
Convert string to underscore.
-
.url_encode(key) ⇒ Object
Encodes a string in a way that makes it suitable for use in a set of query parameters in a URI or in a set of form parameters in a request body.
Class Method Details
.compact(hash) ⇒ Hash
Remove nil value from hash
11 12 13 |
# File 'lib/fat_zebra/util.rb', line 11 def compact(hash) hash.reject { |_, value| value.nil? } end |
.encode_parameters(params) ⇒ Object
Encodes a hash of parameters in a way that’s suitable for use as query parameters in a URI or as form parameters in a request body. This mainly involves escaping special characters from parameter keys and values (e.g. ‘&`).
20 21 22 |
# File 'lib/fat_zebra/util.rb', line 20 def encode_parameters(params) params.map { |k, v| "#{url_encode(k)}=#{url_encode(v)}" }.join('&') end |
.format_dates_in_hash(hash) ⇒ Hash
Format Date attribute in the params
60 61 62 63 64 65 66 |
# File 'lib/fat_zebra/util.rb', line 60 def format_dates_in_hash(hash) hash.each do |(key, value)| hash[key] = value.strftime(DATE_FORMAT) if value.is_a?(DateTime) || value.is_a?(Time) || value.is_a?(Date) end hash end |
.hash_except(hash, *keys) ⇒ Object
48 49 50 51 52 |
# File 'lib/fat_zebra/util.rb', line 48 def hash_except(hash, *keys) copy = hash.dup keys.each { |key| copy.delete(key) } copy end |
.underscore(string) ⇒ Object
Convert string to underscore
39 40 41 42 43 44 45 46 |
# File 'lib/fat_zebra/util.rb', line 39 def underscore(string) string .gsub(/::/, '/') .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr('-', '_') .downcase end |
.url_encode(key) ⇒ Object
Encodes a string in a way that makes it suitable for use in a set of query parameters in a URI or in a set of form parameters in a request body.
28 29 30 |
# File 'lib/fat_zebra/util.rb', line 28 def url_encode(key) CGI.escape(key.to_s).gsub('%5B', '[').gsub('%5D', ']') end |