Class: FantasticRobot::Model::Base
- Inherits:
-
Object
- Object
- FantasticRobot::Model::Base
- Includes:
- ActiveModel::Model, ActiveModel::Serialization, ActiveModel::Serializers::JSON, ActiveModel::Validations
- Defined in:
- lib/fantastic_robot/model/base.rb
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
-
#attributes ⇒ Object
Attribute map for ActiveModel::Serialization.
-
#initialize(attributes = {}) ⇒ Base
constructor
Initializer that converts the fields received if necessary.
-
#to_h ⇒ Object
Proxy to get a serialized version of the object.
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 |
# 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 super(attributes) end |
Instance Method Details
#attributes ⇒ Object
Attribute map for ActiveModel::Serialization.
40 41 42 |
# File 'lib/fantastic_robot/model/base.rb', line 40 def attributes Hash[instance_variables.map{|attrib| [attrib.to_s[1..attrib.to_s.size], nil]}] end |
#to_h ⇒ Object
Proxy to get a serialized version of the object.
45 46 47 |
# File 'lib/fantastic_robot/model/base.rb', line 45 def to_h recursive_serialization(self) end |