Module: FatZebra::Util
- Defined in:
- lib/fat_zebra/util.rb
Constant Summary collapse
- DATE_FORMAT =
'%Y/%m/%d'
- REGEXP_HTTP =
%r{https?://}.freeze
Class Method Summary collapse
-
.camelize(string) ⇒ Object
Convert string to camelize.
- .cleanup_host(uri) ⇒ Object
-
.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
.camelize(string) ⇒ Object
Convert string to camelize
29 30 31 |
# File 'lib/fat_zebra/util.rb', line 29 def camelize(string) string.split('_').map(&:capitalize).join end |
.cleanup_host(uri) ⇒ Object
10 11 12 |
# File 'lib/fat_zebra/util.rb', line 10 def cleanup_host(uri) uri.to_s.gsub(REGEXP_HTTP, '') end |
.compact(hash) ⇒ Hash
Remove nil value from hash
18 19 20 |
# File 'lib/fat_zebra/util.rb', line 18 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. ‘&`).
38 39 40 |
# File 'lib/fat_zebra/util.rb', line 38 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
78 79 80 81 82 83 84 |
# File 'lib/fat_zebra/util.rb', line 78 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
66 67 68 69 70 |
# File 'lib/fat_zebra/util.rb', line 66 def hash_except(hash, *keys) copy = hash.dup keys.each { |key| copy.delete(key) } copy end |
.underscore(string) ⇒ Object
Convert string to underscore
57 58 59 60 61 62 63 64 |
# File 'lib/fat_zebra/util.rb', line 57 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.
46 47 48 |
# File 'lib/fat_zebra/util.rb', line 46 def url_encode(key) CGI.escape(key.to_s).gsub('%5B', '[').gsub('%5D', ']') end |