Class: Kvom::Adapter::Attributes

Inherits:
Object
  • Object
show all
Defined in:
lib/kvom/adapter/attributes.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes, from_db = false) ⇒ Attributes

Returns a new instance of Attributes.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/kvom/adapter/attributes.rb', line 7

def initialize(attributes, from_db = false)
  if from_db
    meta = attributes && attributes.delete("@meta.json")
    @coding = meta && MultiJson.load(meta)["coding"] || {}
    @coded_attributes = attributes
    @attributes = {}
  else
    @coding = {}
    @coded_attributes = {}
    @attributes = attributes ? attributes.dup : {}
  end
end

Instance Method Details

#[](name) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/kvom/adapter/attributes.rb', line 20

def [](name)
  return @attributes[name] if @attributes.key?(name)
  coded_value = @coded_attributes[name]
  @attributes[name] =
      case @coding[name]
      when nil
        coded_value
      when "json"
        MultiJson.load(coded_value)
      when "jsonvalue"
        ::Kvom::Lib::JsonValue.load(coded_value)
      else
        raise "Unexpected coding #{@coding[name]} for attribute #{name}"
      end
end

#[]=(name, value) ⇒ Object



36
37
38
39
40
# File 'lib/kvom/adapter/attributes.rb', line 36

def []=(name, value)
  @coding.delete(name)
  @coded_attributes.delete(name)
  @attributes[name] = value
end

#to_hObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/kvom/adapter/attributes.rb', line 42

def to_h
  @attributes.each do |(name, value)|
    next if @coded_attributes.key?(name)
    if value == nil
      # can happen for (the writer bypassing) new(:property => nil)
      @coded_attributes.delete(name)
    else
      @coded_attributes[name] =
          case value
          when "", true, false
            @coding[name] = "jsonvalue"
            ::Kvom::Lib::JsonValue.dump(value)
          when Array, Hash
            @coding[name] = "json"
            MultiJson.dump(value)
          when String, Numeric
            value
          else
            raise UnsupportedValue, "Unsupported value type #{value.class}"
          end
     end
  end

  if @coding.empty?
    @coded_attributes.delete("@meta.json")
  else
    @coded_attributes["@meta.json"] = MultiJson.dump("coding" => @coding)
  end
  @coded_attributes
end