Module: StarkBank::Utils::API

Defined in:
lib/utils/api.rb

Class Method Summary collapse

Class Method Details

.api_json(entity) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/utils/api.rb', line 8

def self.api_json(entity)
  if entity.is_a?(Hash)
    entity_hash = entity
  else
    entity_hash = {}
    entity.instance_variables.each do |key|
      entity_hash[key[1..-1]] = entity.instance_variable_get(key)
    end
  end
  cast_json_to_api_format(entity_hash)
end

.cast_json_to_api_format(hash) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/utils/api.rb', line 20

def self.cast_json_to_api_format(hash)
  entity_hash = {}
  hash.each do |key, value|
    next if value.nil?

    value = value.is_a?(Date) || value.is_a?(DateTime) || value.is_a?(Time) ? value.strftime('%Y-%m-%d') : value

    if value.is_a?(Array)
      list = []
      value.each do |v|
        list << (v.is_a?(Hash) ? cast_json_to_api_format(v) : v)
      end
      value = list
    end

    entity_hash[StarkBank::Utils::Case.snake_to_camel(key)] = value
  end
  entity_hash
end

.endpoint(resource_name) ⇒ Object



48
49
50
51
52
# File 'lib/utils/api.rb', line 48

def self.endpoint(resource_name)
  kebab = StarkBank::Utils::Case.camel_to_kebab(resource_name)
  kebab.sub!('-log', '/log')
  kebab
end

.from_api_json(resource_maker, json) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/utils/api.rb', line 40

def self.from_api_json(resource_maker, json)
  snakes = {}
  json.each do |key, value|
    snakes[StarkBank::Utils::Case.camel_to_snake(key)] = value
  end
  resource_maker.call(snakes)
end

.last_name(resource_name) ⇒ Object



58
59
60
# File 'lib/utils/api.rb', line 58

def self.last_name(resource_name)
  StarkBank::Utils::Case.camel_to_kebab(resource_name).split('-').last
end

.last_name_plural(resource_name) ⇒ Object



54
55
56
# File 'lib/utils/api.rb', line 54

def self.last_name_plural(resource_name)
  "#{last_name(resource_name)}s"
end