Class: Zermelo::Associations::Singular

Inherits:
Object
  • Object
show all
Defined in:
lib/zermelo/associations/singular.rb

Instance Method Summary collapse

Constructor Details

#initialize(type, parent_klass, parent_id, name) ⇒ Singular

Returns a new instance of Singular.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/zermelo/associations/singular.rb', line 5

def initialize(type, parent_klass, parent_id, name)
  @type = type
  @parent_klass = parent_klass
  @parent_id = parent_id
  @name   = name

  @backend = parent_klass.send(:backend)

  @record_id_key = Zermelo::Records::Key.new(
    :klass  => parent_klass,
    :id     => parent_id,
    :name   => type.to_s,
    :type   => :hash,
    :object => :association
  )

  parent_klass.send(:with_association_data, name.to_sym) do |data|
    @associated_class = data.data_klass
    @lock_klasses     = [data.data_klass] + data.related_klasses
    @inverse          = data.inverse
    @callbacks        = data.callbacks
  end

  raise ':inverse_of must be set' if @inverse.nil?
  @inverse_key = "#{@inverse}_id"
end

Instance Method Details

#key_dumpObject



65
66
67
# File 'lib/zermelo/associations/singular.rb', line 65

def key_dump
  [@backend.key_to_backend_key(@record_id_key), @record_id_key]
end

#valueObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/zermelo/associations/singular.rb', line 50

def value
  v = nil
  @parent_klass.lock(*@lock_klasses) do
    br = @callbacks[:before_read]
    @parent_klass.send(br, @parent_id) if !br.nil? && @parent_klass.respond_to?(br)
    id = @backend.get(@record_id_key)["#{@name}_id"]
    # # TODO maybe: uses hgetall, need separate getter for hash/list/set
    # @backend.get_hash_value(@record_id_key, "#{@name}_id")
    v = @associated_class.send(:load, id) unless id.nil?
    ar = @callbacks[:after_read]
    @parent_klass.send(ar, @parent_id, v) if !ar.nil? && @parent_klass.respond_to?(ar)
  end
  v
end

#value=(record) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/zermelo/associations/singular.rb', line 32

def value=(record)
  if record.nil?
    @parent_klass.lock(*@lock_klasses) do
      _clear(:callbacks => true)
    end
  else
    raise 'Invalid record class' unless record.is_a?(@associated_class)
    raise 'Record must have been saved' unless record.persisted?
    @parent_klass.lock(*@lock_klasses) do
      opts = {:callbacks => true}
      if :sorted_set.eql?(_inverse.type)
        opts[:score] = @parent_klass.find_by_id!(@parent_id).send(@inverse_sort_key.to_sym).to_f
      end
      _set(opts, record.id)
    end
  end
end