Module: FatZebra::Util

Defined in:
lib/fat_zebra/util.rb

Constant Summary collapse

DATE_FORMAT =
'%Y/%m/%d'.freeze
REGEXP_HTTP =
%r{http[s]?\:\/\/}

Class Method Summary collapse

Class Method Details

.camelize(string) ⇒ Object

Convert string to camelize

Examples:

camelize('my_model') => 'MyModel'

Parameters:

  • (String)


27
28
29
# File 'lib/fat_zebra/util.rb', line 27

def camelize(string)
  string.split('_').map(&:capitalize).join
end

.cleanup_host(uri) ⇒ Object



8
9
10
# File 'lib/fat_zebra/util.rb', line 8

def cleanup_host(uri)
  uri.gsub(REGEXP_HTTP, '')
end

.compact(hash) ⇒ Hash

Remove nil value from hash

Returns:

  • (Hash)


16
17
18
# File 'lib/fat_zebra/util.rb', line 16

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. ‘&`).



36
37
38
# File 'lib/fat_zebra/util.rb', line 36

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

Parameters:

  • params (Hash)

Returns:

  • (Hash)

    date formated params



76
77
78
79
80
81
82
# File 'lib/fat_zebra/util.rb', line 76

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



64
65
66
67
68
# File 'lib/fat_zebra/util.rb', line 64

def hash_except(hash, *keys)
  copy = hash.dup
  keys.each { |key| copy.delete(key) }
  copy
end

.underscore(string) ⇒ Object

Convert string to underscore

Examples:

underscore('MyModel') => 'my_model'

Parameters:

  • (String)


55
56
57
58
59
60
61
62
# File 'lib/fat_zebra/util.rb', line 55

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.



44
45
46
# File 'lib/fat_zebra/util.rb', line 44

def url_encode(key)
  CGI.escape(key.to_s).gsub('%5B', '[').gsub('%5D', ']')
end