Class: Thron::Entity::Base

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/thron/entity/base.rb

Direct Known Subclasses

Image

Constant Summary collapse

TIME_REGEX =
/\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.+/
DATE_REGEX =
/\A\d{4}-\d{2}-\d{2}/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Base

Returns a new instance of Base.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/thron/entity/base.rb', line 21

def initialize(hash = {})
  @table = {}
  hash.each do |k,v|
    k = k.to_s.snakecase.to_sym
    @table[k] = case v
                when Hash
                  self.class.new(v)
                when Array
                  if v.first.is_a?(Hash)
                    v.map { |e| self.class.new(e) }
                  else
                    v
                  end
                when TIME_REGEX
                  Time::parse(v)
                when DATE_REGEX
                  Date::parse(v)
                else
                  v
                end
    new_ostruct_member(k)
  end
end

Class Method Details

.factory(args) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/thron/entity/base.rb', line 12

def self.factory(args)
  case args
  when Hash
    new(args)
  when Array
    args.map { |data| new(data) }
  end
end

Instance Method Details

#to_hObject



45
46
47
48
49
# File 'lib/thron/entity/base.rb', line 45

def to_h
  self.each_pair.reduce({}) do |acc, (k,v)|
    acc[k] = fetch_value(v, :to_h); acc
  end
end

#to_payloadObject



51
52
53
54
55
56
# File 'lib/thron/entity/base.rb', line 51

def to_payload
  self.each_pair.reduce({}) do |acc, (k,v)|
    k = k.to_s.camelize_low
    acc[k] = fetch_value(v, :to_payload); acc
  end
end