Module: Keymaker::Serialization

Includes:
ActiveModel::Serialization
Defined in:
lib/keymaker/serialization.rb

Constant Summary collapse

COERCION_PROCS =
Hash.new(->(v){v}).tap do |procs|
  procs[Integer] = ->(v){ v.to_i }
  procs[DateTime] = ->(v) do
    case v
    when Time
      Time.at(v)
    when String
      v.to_time
    else
      Time.now.utc
    end
  end
end

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
# File 'lib/keymaker/serialization.rb', line 4

def self.included(base)
  base.define_model_callbacks :save, :create
end

Instance Method Details

#attributesObject



41
42
43
44
45
# File 'lib/keymaker/serialization.rb', line 41

def attributes
  Hash.new{|h,k| h[k] = send(k) }.tap do |hash|
    self.class.properties.each{|property| hash[property.to_s] }
  end
end

#coerce(value, type) ⇒ Object



37
38
39
# File 'lib/keymaker/serialization.rb', line 37

def coerce(value,type)
  COERCION_PROCS[type].call(value)
end

#process_attr(key, value) ⇒ Object



33
34
35
# File 'lib/keymaker/serialization.rb', line 33

def process_attr(key, value)
  send("#{key}=", coerce(value,self.class.property_traits[key]))
end

#process_attrs(attrs) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/keymaker/serialization.rb', line 22

def process_attrs(attrs)
  attrs.symbolize_keys!
  self.class.properties.delete_if{|p| p == :node_id}.each do |property|
    if property == :active_record_id
      process_attr(property, attrs[:id].present? ? attrs[:id] : attrs[:active_record_id])
    else
      process_attr(property, attrs[property])
    end
  end
end