Class: Zermelo::Associations::HasOne
- Inherits:
-
Object
- Object
- Zermelo::Associations::HasOne
- Defined in:
- lib/zermelo/associations/has_one.rb
Instance Method Summary collapse
-
#initialize(parent, name) ⇒ HasOne
constructor
A new instance of HasOne.
- #value ⇒ Object
- #value=(record) ⇒ Object
Constructor Details
#initialize(parent, name) ⇒ HasOne
Returns a new instance of HasOne.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/zermelo/associations/has_one.rb', line 5 def initialize(parent, name) @parent = parent @backend = parent.send(:backend) # TODO would be better as a 'has_one' hash, a bit like belongs_to @record_id_key = Zermelo::Records::Key.new( :klass => parent.class.send(:class_key), :id => parent.id, :name => "#{name}_id", :type => :string, :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 end |
Instance Method Details
#value ⇒ Object
27 28 29 30 31 32 33 34 35 |
# File 'lib/zermelo/associations/has_one.rb', line 27 def value @parent.class.lock(*@associated_class) do if id = @backend.get(@record_id_key) @associated_class.send(:load, id) else nil end end end |
#value=(record) ⇒ Object
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 63 64 65 66 67 68 69 70 71 |
# File 'lib/zermelo/associations/has_one.rb', line 37 def value=(record) if record.nil? @parent.class.lock(*@lock_klasses) do id = @backend.get(@record_id_key) unless id.nil? r = @associated_class.send(:load, id) unless r.nil? bc = @callbacks[:before_clear] if bc.nil? || !@parent.respond_to?(bc) || !@parent.send(bc, r).is_a?(FalseClass) delete_without_lock(r) ac = @callbacks[:after_clear] @parent.send(ac, r) if !ac.nil? && @parent.respond_to?(ac) end end 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) unless @inverse.nil? @associated_class.send(:load, record.id).send("#{@inverse}=", @parent) end new_txn = @backend.begin_transaction @backend.set(@record_id_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 |