Class: Preferable::Coder

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

Instance Method Summary collapse

Instance Method Details

#dump(obj) ⇒ Object



3
4
5
# File 'lib/preferable/coder.rb', line 3

def dump(obj)
  ActiveSupport::JSON.encode(obj) if obj.is_a?(Hash) && obj.present?
end

#load(string) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/preferable/coder.rb', line 7

def load(string)
  return {} if string.blank?
  return string if string.is_a?(Hash)
  return legacy_load(string) if string.is_a?(String) && string =~ /^---/

  begin
    obj = ActiveSupport::JSON.decode(string) || {}
    raise ActiveRecord::SerializationTypeMismatch, "Attribute was supposed to be a Hash, but was a #{obj.class}" unless obj.is_a?(Hash)
    obj
  rescue MultiJson::DecodeError
    {}
  end
end