Module: Mollie::Util

Defined in:
lib/mollie/util.rb

Constant Summary collapse

CAMELIZE_NESTED =
[
  :lines,
  "lines",
  :recurring,
  "recurring",
  :billing_address,
  "billing_address",
  :shipping_address,
  "shipping_address"
].freeze

Class Method Summary collapse

Class Method Details

.camelize(term) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/mollie/util.rb', line 59

def camelize(term)
  string = term.to_s
  string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/, &:downcase)
  string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{Regexp.last_match(1)}#{Regexp.last_match(2).capitalize}" }
  string.gsub!('/'.freeze, '::'.freeze)
  string
end

.camelize_keys(object) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/mollie/util.rb', line 28

def camelize_keys(object)
  case object
  when Hash
    object.each_with_object({}) do |(key, value), camelized|
      camelized[camelize(key)] = if CAMELIZE_NESTED.include?(key)
        camelize_keys(value)
      else
        value
      end
    end
  when Array
    object.map { |value| camelize_keys(value) }
  else
    object
  end
end

.extract_id(links, type) ⇒ Object



83
84
85
86
87
88
# File 'lib/mollie/util.rb', line 83

def extract_id(links, type)
  href = extract_url(links, type)
  return if href.nil?
  uri = URI.parse(href)
  File.basename(uri.path)
end

.extract_url(links, type) ⇒ Object



79
80
81
# File 'lib/mollie/util.rb', line 79

def extract_url(links, type)
  links && links[type] && links[type]['href']
end

.nested_openstruct(obj) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/mollie/util.rb', line 67

def nested_openstruct(obj)
  if obj.is_a?(Hash)
    obj.each_with_object(OpenStruct.new) do |(key, value), openstructed|
      openstructed[key] = nested_openstruct(value)
    end
  elsif obj.is_a?(Array)
    obj.map { |v| nested_openstruct(v) }
  else
    obj
  end
end

.nested_underscore_keys(obj) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/mollie/util.rb', line 5

def nested_underscore_keys(obj)
  if obj.is_a?(Hash)
    obj.each_with_object({}) do |(key, value), underscored|
      underscored[underscore(key)] = nested_underscore_keys(value)
    end
  elsif obj.is_a?(Array)
    obj.map { |v| nested_underscore_keys(v) }
  else
    obj
  end
end

.pluralize(string) ⇒ Object

Dirty pluralize function, but currently holds for all required plurals Not worth to include another library like ActiveSupport



55
56
57
# File 'lib/mollie/util.rb', line 55

def pluralize(string)
  "#{string}s"
end

.underscore(string) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/mollie/util.rb', line 45

def underscore(string)
  string.to_s.gsub(/::/, '/')
        .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
        .gsub(/([a-z\d])([A-Z])/, '\1_\2')
        .tr('-', '_')
        .downcase.to_s
end