Module: BetterSerialization
- Included in:
- ActiveRecord::Base
- Defined in:
- lib/better_serialization.rb
Defined Under Namespace
Classes: JsonSerializer
Instance Method Summary collapse
-
#json_serialize(*attrs) ⇒ Object
Options options is the last parameter (a hash): *
:gzip
- uses gzip before and after serialization. - #json_serialized_attributes ⇒ Object
-
#marshal_serialize(*attrs) ⇒ Object
Options *
gzip
- uses gzip before marshalling and unmarshalling.
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 ifraw
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) = attrs.last.is_a?(Hash) ? attrs.pop : {} = {:instantiate => true}.merge() attrs.each do |attribute| define_method "#{attribute}=" do |value| super(JsonSerializer.new().to_json(value)) end define_method attribute do JsonSerializer.new().from_json(self[attribute]) end (@json_serialized_attributes||={})[attribute.to_s]= end end |
#json_serialized_attributes ⇒ Object
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) = 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 [:gzip] super(marshalled_value) end define_method attribute do return nil if self[attribute].nil? value = Zlib::Inflate.inflate(self[attribute]) if [:gzip] Marshal.load(value || self[attribute]) end end end |