Class: SerializableAttributes::Hash

Inherits:
AttributeType show all
Defined in:
lib/serializable_attributes/types.rb

Instance Method Summary collapse

Methods inherited from AttributeType

#default, #type_for

Constructor Details

#initialize(options = {}) ⇒ Hash

Returns a new instance of Hash.



101
102
103
104
105
106
107
108
109
# File 'lib/serializable_attributes/types.rb', line 101

def initialize(options = {})
  super
  @key_type = String.new
  @types    = (options[:types] || {})
  @types.keys.each do |key|
    value = @types.delete(key)
    @types[key.to_s] = type_for(value)
  end
end

Instance Method Details

#encode(input) ⇒ Object



122
123
124
125
126
127
128
# File 'lib/serializable_attributes/types.rb', line 122

def encode(input)
  return nil if input.blank?
  input.each do |key, value|
    type = @types[key] || @key_type
    input[key] = type.encode(value)
  end
end

#parse(input) ⇒ Object



111
112
113
114
115
116
117
118
119
120
# File 'lib/serializable_attributes/types.rb', line 111

def parse(input)
  return nil if input.blank?
  input.keys.each do |key|
    value = input.delete(key)
    key_s = @key_type.parse(key)
    type  = @types[key_s] || @key_type
    input[key_s] = type.parse(value)
  end
  input
end