Class: Booker::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/booker/model.rb

Constant Summary collapse

CONSTANTIZE_MODULE =
Booker

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Model

Returns a new instance of Model.



5
6
7
8
9
10
11
# File 'lib/booker/model.rb', line 5

def initialize(options = {})
  @attributes = []
  options.each do |k, v|
    send(:"#{k}=", v)
    @attributes << k.to_sym
  end
end

Class Method Details

.constantize(key) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/booker/model.rb', line 62

def self.constantize(key)
  begin
    self::CONSTANTIZE_MODULE.const_get key.to_s.camelize.singularize
  rescue NameError
    nil
  end
end

.from_hash(hash) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/booker/model.rb', line 34

def self.from_hash(hash)
  model = self.new
  hash.each do |k, v|
    if model.respond_to?(:"#{k}")
      constantized = self.constantize(k)
      if constantized
        if v.is_a?(Array) && v.first.is_a?(Hash)
          model.send(:"#{k}=", constantized.from_list(v))
          next
        elsif v.is_a? Hash
          model.send(:"#{k}=", constantized.from_hash(v))
          next
        end
      end
      if v.is_a?(String) && v.start_with?('/Date(')
        model.send(:"#{k}=", try(:time_from_booker_datetime, v) || v)
        next
      end
      model.send(:"#{k}=", v)
    end
  end
  model
end

.from_list(array) ⇒ Object



60
# File 'lib/booker/model.rb', line 60

def self.from_list(array); array.map { |item| self.from_hash(item) }; end

Instance Method Details

#to_hashObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/booker/model.rb', line 13

def to_hash
  hash = {}
  @attributes.each do |attr|
    value = self.send(attr)
    if value.is_a? Array
      new_value = hash_list(value)
    elsif value.is_a? Booker::Model
      new_value = value.to_hash
    elsif value.is_a? Time
      new_value = self.class.try(:time_to_booker_datetime, value) || value
    elsif value.is_a? Date
      time = value.in_time_zone
      new_value = self.class.try(:time_to_booker_datetime, time) || value
    else
      new_value = value
    end
    hash[attr] = new_value
  end
  hash
end

#to_jsonObject



58
# File 'lib/booker/model.rb', line 58

def to_json; Oj.dump(to_hash, mode: :compat); end