Module: StarkInfra::Utils::API

Defined in:
lib/utils/api.rb

Class Method Summary collapse

Class Method Details

.api_json(entity) ⇒ Object

[View source]

21
22
23
24
# File 'lib/utils/api.rb', line 21

def self.api_json(entity)
  built_hash = build_entity_hash(entity)
  cast_json_to_api_format(built_hash)
end

.build_entity_hash(entity) ⇒ Object

[View source]

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

def self.build_entity_hash(entity)
  if entity.is_a?(Hash)
    entity_hash = entity
  else
    entity_hash = {}
    entity.instance_variables.each do |key|
      variable = entity.instance_variable_get(key)
      entity_hash[key[1..-1]] = variable.is_a?(StarkInfra::Utils::Resource) ? build_entity_hash(variable) : entity.instance_variable_get(key)
    end
  end
  entity_hash
end

.cast_json_to_api_format(hash) ⇒ Object

[View source]

26
27
28
29
30
31
32
33
34
# File 'lib/utils/api.rb', line 26

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

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

.endpoint(resource_name) ⇒ Object

[View source]

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

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

.from_api_json(resource_maker, json) ⇒ Object

[View source]

49
50
51
52
53
54
55
56
# File 'lib/utils/api.rb', line 49

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

  resource_maker.call(snakes)
end

.last_name(resource_name) ⇒ Object

[View source]

75
76
77
# File 'lib/utils/api.rb', line 75

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

.last_name_plural(resource_name) ⇒ Object

[View source]

65
66
67
68
69
70
71
72
73
# File 'lib/utils/api.rb', line 65

def self.last_name_plural(resource_name)
  base = last_name(resource_name)

  return base if base[-1].eql?('s')
  return "#{base}s" if base[-2..-1].eql?('ey')
  return "#{base[0...-1]}ies" if base[-1].eql?('y')

  "#{base}s"
end

.parse_value(value) ⇒ Object

[View source]

36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/utils/api.rb', line 36

def self.parse_value(value)
  return value.strftime('%Y-%m-%d') if value.is_a?(Date)
  return value.strftime('%Y-%m-%dT%H:%M:%S+00:00') if value.is_a?(DateTime) || value.is_a?(Time)
  return cast_json_to_api_format(value) if value.is_a?(Hash)
  return value unless value.is_a?(Array)

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