Class: Zermelo::Associations::BelongsTo
- Inherits:
-
Object
- Object
- Zermelo::Associations::BelongsTo
- Defined in:
- lib/zermelo/associations/belongs_to.rb
Instance Method Summary collapse
-
#initialize(parent, name) ⇒ BelongsTo
constructor
NB a single instance of this class doesn’t need to care about the hash used for storage, that should be done in the save method of the parent.
- #value ⇒ Object
- #value=(record) ⇒ Object
Constructor Details
#initialize(parent, name) ⇒ BelongsTo
NB a single instance of this class doesn’t need to care about the hash used for storage, that should be done in the save method of the parent
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/zermelo/associations/belongs_to.rb', line 10 def initialize(parent, name) @parent = parent @name = name @backend = parent.send(:backend) @record_ids_key = Zermelo::Records::Key.new( :klass => parent.class.send(:class_key), :id => parent.id, :name => 'belongs_to', :type => :hash, :object => :association ) parent.class.send(:with_association_data, name.to_sym) do |data| @associated_class = data.data_klass @lock_klasses = [data.data_klass] + data. @inverse = data.inverse @callbacks = data.callbacks end raise ':inverse_of must be set' if @inverse.nil? @inverse_key = "#{name}_id" end |
Instance Method Details
#value ⇒ Object
64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/zermelo/associations/belongs_to.rb', line 64 def value @parent.class.lock(*@lock_klasses) do # FIXME uses hgetall, need separate getter for hash/list/set if id = @backend.get(@record_ids_key)[@inverse_key.to_s] # if id = @backend.get_hash_value(@record_ids_key, @inverse_key.to_s) @associated_class.send(:load, id) else nil end end end |
#value=(record) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/zermelo/associations/belongs_to.rb', line 35 def value=(record) if record.nil? @parent.class.lock(*@lock_klasses) do r = @associated_class.send(:load, @backend.get(@record_ids_key)[@inverse_key.to_s]) bc = @callbacks[:before_clear] if bc.nil? || !@parent.respond_to?(bc) || !@parent.send(bc, r).is_a?(FalseClass) new_txn = @backend.begin_transaction @backend.delete(@record_ids_key, @inverse_key) @backend.commit_transaction if new_txn ac = @callbacks[:after_clear] @parent.send(ac, r) if !ac.nil? && @parent.respond_to?(ac) end end else raise 'Invalid record class' unless record.is_a?(@associated_class) raise 'Record must have been saved' unless record.persisted? @parent.class.lock(*@lock_klasses) do bs = @callbacks[:before_set] if bs.nil? || !@parent.respond_to?(bs) || !@parent.send(bs, r).is_a?(FalseClass) new_txn = @backend.begin_transaction @backend.add(@record_ids_key, @inverse_key => record.id) @backend.commit_transaction if new_txn as = @callbacks[:after_set] @parent.send(as, record) if !as.nil? && @parent.respond_to?(as) end end end end |