Skip to content

Instantly share code, notes, and snippets.

@jpr5
Created Feb 25, 2011
Embed
What would you like to do?
DM: lazy-loaded properties materialized in hooks (:save) reset parental reference updates for children
#!/usr/bin/ruby
require 'rubygems'
require 'data_objects' # current master @ ed1ceefc
require 'dm-core' # current master @ 73860575
require 'dm-migrations' # current master @ ab608e81
class Order
include ::DataMapper::Resource
property :id, Serial
has 0..n, :order_items
end
class OrderItem
include ::DataMapper::Resource
property :id, Serial
property :queues, String, :default => '', :lazy => true
belongs_to :order
before :save do
if $LAZY_LOAD
warn "materializing lazy_loaded property"
self.queues
end
end
end
::DataMapper.setup(:default, 'mysql://127.0.0.1/test')
$LAZY_LOAD = false
2.times do |i|
::DataMapper.auto_migrate!
warn "\n--- pass #{i} (lazy load property in save hook == #{$LAZY_LOAD})\n"
order = Order.create
order_item = OrderItem.create(:queues => 'balls', :order => order)
new_order = Order.create
order.order_items.all.each do |item|
warn "item #{item.id} has order #{item.order.id}, updating with new_order #{new_order.id}"
item.update(:order => new_order)
if item.order.id == new_order.id
warn "EXPECTED: item #{item.id} now has order #{item.order.id}"
else
# NOTE: item.dirty? == false, and it's still the wrong value after item.reload.
warn "NOT EXPECTED: item #{item.id} now has order #{item.order.id} (wanted order #{new_order.id})"
end
end
# Second time through, materialize the lazy-loaded property.
$LAZY_LOAD = true
end
$ ruby child_update_fail.rb
--- pass 0 (lazy load property in save hook == false)
item 1 has order 1, updating with new_order 2
EXPECTED: item 1 now has order 2
--- pass 1 (lazy load property in save hook == true)
materializing lazy_loaded property
item 1 has order 1, updating with new_order 2
materializing lazy_loaded property
NOT EXPECTED: item 1 now has order 1 (wanted order 2)
$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment