Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/serialize_json.rb

Class Method Summary collapse

Class Method Details

.serialize_json(attribute, opts = {}) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/active_record/serialize_json.rb', line 68

def self.serialize_json(attribute, opts = {})
  sj = SerializeJSON.new(attribute, opts)

  after_save  sj
  before_save sj

  unless respond_to?(:serialize_json_attributes)
    cattr_accessor :serialize_json_attributes
    self.serialize_json_attributes = {}
  end
  serialize_json_attributes[sj.attribute] = sj

  if ::ActiveRecord::VERSION::MAJOR >= 3
    class_eval do
      after_find do |record|
        serialize_json_attributes.each do |attribute, sj|
          record.instance_eval do
            write_attribute(attribute, sj.deserialize(record))
          end
        end
      end
    end
  else
    class_eval do
      define_method(:after_find) do
        super if defined? super
        self.class.serialize_json_attributes.each do |attribute, sj|
          write_attribute(attribute, sj.deserialize(self))
        end
      end
    end
  end
end