diff options
author | Brad Gessler <brad@bradgessler.com> | 2012-02-12 15:33:14 -0800 |
---|---|---|
committer | Brad Gessler <brad@polleverywhere.com> | 2013-02-12 23:58:37 -0800 |
commit | d20eed6540b7cc264583244088344f73436292b7 (patch) | |
tree | 896db21b65b617edce80318fa0e83042de131152 | |
parent | fc875ae8a3ee41b9d11683fbd560edabebfe1a2f (diff) | |
download | hashie-d20eed6540b7cc264583244088344f73436292b7.tar.gz |
Added support for deferred properties to Dash
-rw-r--r-- | lib/hashie/dash.rb | 9 | ||||
-rw-r--r-- | spec/hashie/dash_spec.rb | 15 |
2 files changed, 22 insertions, 2 deletions
diff --git a/lib/hashie/dash.rb b/lib/hashie/dash.rb index bdc256d..8a1f6f7 100644 --- a/lib/hashie/dash.rb +++ b/lib/hashie/dash.rb @@ -110,8 +110,13 @@ module Hashie 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 diff --git a/spec/hashie/dash_spec.rb b/spec/hashie/dash_spec.rb index 1267651..1e1edc9 100644 --- a/spec/hashie/dash_spec.rb +++ b/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 @@ describe DashTest do 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) |