Class: FantasticRobot::Model::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model, ActiveModel::Serialization, ActiveModel::Serializers::JSON, ActiveModel::Validations
Defined in:
lib/fantastic_robot/model/base.rb

Direct Known Subclasses

Attachment::Base, Chat, File, Message, Update, User

Constant Summary collapse

FIELD_CONVERSIONS =

As the models include a lot of different objects related, we build a conversion hash that indicates the type of objects required in special fields.

{}

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Base

Initializer that converts the fields received if necessary



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/fantastic_robot/model/base.rb', line 15

def initialize(attributes = {})

  # Define a setter for each field that need to be converted
  self.class::FIELD_CONVERSIONS.each do |field_name, field_type|
    self.class.send(:define_method, "#{field_name}=") do |value|
      if (value.is_a?(Array))
        # If we receive an array, process each value
        value.map! do |v|
          # Convert each object except if it is already converted or nil
          v = ((v.class == field_type || v.nil?) ? v : field_type.new(v))
        end
      else
        # If it isn't an array, try to convert the object
        value = field_type.new(value) unless (value.class == field_type || value.nil?)
      end

      # Set the result
      instance_variable_set("@#{field_name}", value)
    end
  end

  attributes = attributes.delete_if{|k, v| !self.respond_to?("#{k}=")}

  super(attributes)
end

Instance Method Details

#attributesObject

Attribute map for ActiveModel::Serialization.



42
43
44
# File 'lib/fantastic_robot/model/base.rb', line 42

def attributes
  Hash[instance_variables.map{|attrib| [attrib.to_s[1..attrib.to_s.size], nil]}]
end

#to_hObject

Proxy to get a serialized version of the object.



47
48
49
# File 'lib/fantastic_robot/model/base.rb', line 47

def to_h
  recursive_serialization(self)
end