Module: BetterSerialization

Included in:
ActiveRecord::Base
Defined in:
lib/better_serialization.rb

Defined Under Namespace

Classes: JsonSerializer

Instance Method Summary collapse

Instance Method Details

#json_serialize(*attrs) ⇒ Object

Options

options is the last parameter (a hash):

  • :gzip - uses gzip before and after serialization. Slight speed hit, but can save a lot of hard drive space.

  • :instantiate - if false, it will return the raw decoded json and not attempt to instantiate ActiveRecord objects. Defaults to true.

  • :with_indifferent_access - if true, it will return the raw decoded json as a hash with indifferent access. This can be handy because json doesn’t have a concept of symbols, so it gets annoying when you’re using a field as a key-value store

  • :default - A proc that gets called when the field is null

  • :class_name - If ActiveRecord::Base.include_root_in_json is false, you will need this option so that we can figure out which AR class to instantiate (not applicable if raw is true)



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/better_serialization.rb', line 106

def json_serialize(*attrs)
  options = attrs.last.is_a?(Hash) ? attrs.pop : {}
  options = {:instantiate => true}.merge(options)
  
  attrs.each do |attribute|
    define_method "#{attribute}=" do |value|
      super(JsonSerializer.new(options).to_json(value))
    end
    
    define_method attribute do
      JsonSerializer.new(options).from_json(self[attribute])
    end

    (@json_serialized_attributes||={})[attribute.to_s]=options
  end
end

#json_serialized_attributesObject



123
124
125
# File 'lib/better_serialization.rb', line 123

def json_serialized_attributes
  @json_serialized_attributes || {}
end

#marshal_serialize(*attrs) ⇒ Object

Options

  • gzip - uses gzip before marshalling and unmarshalling. Slight speed hit, but can save a lot of hard drive space.



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/better_serialization.rb', line 74

def marshal_serialize(*attrs)
  options = attrs.last.is_a?(Hash) ? attrs.pop : {}
  
  attrs.each do |attribute|
    define_method "#{attribute}=" do |value|
      marshalled_value = Marshal.dump(value)
      marshalled_value = Zlib::Deflate.deflate(marshalled_value) if options[:gzip]
      super(marshalled_value)
    end
    
    define_method attribute do
      return nil if self[attribute].nil?
      
      value = Zlib::Inflate.inflate(self[attribute]) if options[:gzip]
      Marshal.load(value || self[attribute])
    end
  end
end