Module: AutoSerialize::ClassMethods

Defined in:
lib/autoserialize.rb

Instance Method Summary collapse

Instance Method Details

#autoserialize(attribute, format = :json, db_column = nil, default_value = {}) ⇒ Object



10
11
12
13
14
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
40
41
42
# File 'lib/autoserialize.rb', line 10

def autoserialize(attribute, format=:json, db_column=nil, default_value={})
  format = validate_serialization_format!(format)
  db_column ||= :"#{attribute}_#{format}"
  class_name = self.name

  options_str = ''
  if default_value.respond_to?('with_indifferent_access')
    options_str += '.with_indifferent_access'
  end
  default_value = default_value.inspect

  define_methods_str = <<END_DEFINE_METHODS_STRING
    def save_#{attribute}
      self.#{db_column} = #{class_name}.to_#{format}(@#{attribute}) if @#{attribute}
    end
    before_validation :save_#{attribute}

    def #{attribute}
      return @#{attribute} if @#{attribute}
      @#{attribute} = ( self.#{db_column} ? #{class_name}.from_#{format}(self.#{db_column}) || #{default_value} : #{default_value} )#{options_str}
    end

    def #{attribute}=(attr)
      self.#{db_column} = #{class_name}.to_#{format}(attr)
    end

    def #{db_column}=(attr_#{format})
      self[:#{db_column}] = attr_#{format}
      @#{attribute} = nil # Clear the cached #{attribute}
    end
END_DEFINE_METHODS_STRING
  self.send(:class_eval, define_methods_str)
end

#from_json(object_str) ⇒ Object



47
48
49
50
# File 'lib/autoserialize.rb', line 47

def from_json(object_str)
  return nil if object_str == "null"
  ActiveSupport::JSON.decode(object_str)
end

#to_json(object) ⇒ Object



44
45
46
# File 'lib/autoserialize.rb', line 44

def to_json(object)
  object.to_json
end