class Rmodel::BaseMapper

Attributes

key_op[RW]
primary_key[RW]

Public Class Methods

new(model) click to toggle source
# File lib/rmodel/base_mapper.rb, line 3
def initialize(model)
  @model = model
  self.primary_key = :id
  self.key_op = :to_sym
  @attributes = {}
end

Public Instance Methods

define_attribute(attr, mapper = DummyMapper.instance) click to toggle source
# File lib/rmodel/base_mapper.rb, line 10
def define_attribute(attr, mapper = DummyMapper.instance)
  @attributes[attr] = mapper
  self
end
define_attributes(*attributes) click to toggle source
# File lib/rmodel/base_mapper.rb, line 15
def define_attributes(*attributes)
  attributes.each { |attr| define_attribute(attr) }
  self
end
define_timestamps() click to toggle source
# File lib/rmodel/base_mapper.rb, line 20
def define_timestamps
  define_attributes :created_at, :updated_at
end
deserialize(hash) click to toggle source
# File lib/rmodel/base_mapper.rb, line 24
def deserialize(hash)
  return nil if hash.nil?

  uni_hash = UniHash.new(hash, key_op)

  object = @model.new
  object.id = uni_hash[primary_key] if object.respond_to?(:id)
  @attributes.each do |attr, mapper|
    deserialized = mapper.deserialize(uni_hash[attr])
    object.public_send "#{attr}=", deserialized
  end
  object
end
serialize(object, id_included) click to toggle source
# File lib/rmodel/base_mapper.rb, line 38
def serialize(object, id_included)
  return nil if object.nil?

  uni_hash = UniHash.new({}, key_op)
  @attributes.each do |attr, mapper|
    serialized = mapper.serialize(object.public_send(attr), id_included)
    uni_hash[attr] = serialized
  end
  if id_included && object.respond_to?(:id)
    uni_hash[primary_key] = object.id
  end
  uni_hash.to_hash
end