Skip to content

Commit

Permalink
Merge pull request #34 from bradgessler/master
Browse files Browse the repository at this point in the history
Deferred defaults for Dash
  • Loading branch information
jch committed Feb 13, 2013
2 parents fc875ae + d20eed6 commit 2cb0865
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/hashie/dash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions spec/hashie/dash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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') }
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 2cb0865

Please sign in to comment.