Browse files

Merge pull request #34 from bradgessler/master

Deferred defaults for Dash
  • Loading branch information...
2 parents fc875ae + d20eed6 commit 2cb0865e1a9f064c988a8dcd180f89c0153f9762 @jch jch committed Feb 13, 2013
Showing with 22 additions and 2 deletions.
  1. +7 −2 lib/hashie/dash.rb
  2. +15 −0 spec/hashie/dash_spec.rb
View
9 lib/hashie/dash.rb
@@ -110,8 +110,13 @@ def initialize(attributes = {}, &block)
def [](property)
assert_property_exists! property
value = super(property.to_s)
- yield value if block_given?
- value
+ # If the value is a lambda, proc, or whatever answers to call, eval the thing!
+ if value.is_a? Proc
+ self[property] = value.call # Set the result of the call as a value
+ else
+ yield value if block_given?
+ value
+ end
end
# Set a value on the Dash in a Hash-like way. Only works
View
15 spec/hashie/dash_spec.rb
@@ -26,6 +26,10 @@ class DashDefaultTest < Hashie::Dash
property :aliases, :default => ["Snake"]
end
+class DeferredTest < Hashie::Dash
+ property :created_at, :default => Proc.new { Time.now }
+end
+
describe DashTest do
subject { DashTest.new(:first_name => 'Bob', :email => 'bob@example.com') }
@@ -100,6 +104,17 @@ class DashDefaultTest < Hashie::Dash
end
end
+ context 'reading from deferred properties' do
+ it 'should evaluate proc after initial read' do
+ DeferredTest.new['created_at'].should be_instance_of(Time)
+ end
+
+ it "should not evalute proc after subsequent reads" do
+ deferred = DeferredTest.new
+ deferred['created_at'].object_id.should == deferred['created_at'].object_id
+ end
+ end
+
describe '.new' do
it 'fails with non-existent properties' do
lambda { described_class.new(:bork => '') }.should raise_error(NoMethodError)

0 comments on commit 2cb0865

Please sign in to comment.