Class: BetterSerialization::JsonSerializer

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ JsonSerializer

Returns a new instance of JsonSerializer.



7
8
9
# File 'lib/better_serialization.rb', line 7

def initialize(options)
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/better_serialization.rb', line 5

def options
  @options
end

Instance Method Details

#from_json(attribute) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/better_serialization.rb', line 17

def from_json(attribute)
  return options[:default].try(:call) if attribute.nil?

  json = options[:gzip] ? Zlib::Inflate.inflate(attribute) : attribute
  decoded = ActiveSupport::JSON.decode(json)

  if options[:with_indifferent_access]
    return decoded.respond_to?(:with_indifferent_access) ? decoded.with_indifferent_access : decoded
  end
  return decoded if !options[:instantiate]

  result = deserialize(attribute, [decoded].flatten)
  return decoded.is_a?(Array) ? result : result.first
end

#to_json(object) ⇒ Object



11
12
13
14
15
# File 'lib/better_serialization.rb', line 11

def to_json(object)
  json = object.to_json
  json = Zlib::Deflate.deflate(json) if options[:gzip]
  json
end