summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDaniel Doubrovkine (dB.) @dblockdotorg <dblock@dblock.org>2015-02-02 11:35:54 -0500
committerDaniel Doubrovkine (dB.) @dblockdotorg <dblock@dblock.org>2015-02-02 11:35:54 -0500
commit7f63f343524d40d409e184004b809af382b0002d (patch)
tree9d947b688ed35aee0ff5c3661b15f92b125e674e
parent4f597934ff70ba0a4ff4abdbdbdd558aa856f604 (diff)
parent25567b512a95e77c9dbb8ab389f522f2ae6220ed (diff)
downloadhashie-7f63f343524d40d409e184004b809af382b0002d.tar.gz
Merge pull request #271 from gregory/defaults_based_on_self
provide self as context when evaluating default
-rw-r--r--CHANGELOG.md1
-rw-r--r--lib/hashie/dash.rb3
-rw-r--r--spec/hashie/dash_spec.rb13
3 files changed, 16 insertions, 1 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 970b66f..4333585 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,6 @@
## Next
+* [#271](https://github.com/intridea/hashie/pull/271): Added ability to define defaults based on current hash - [@gregory](https://github.com/gregory).
* [#247](https://github.com/intridea/hashie/pull/247): Fixed #stringify_keys and #symbolize_keys collision with ActiveSupport - [@bartoszkopinski](https://github.com/bartoszkopinski).
* [#249](https://github.com/intridea/hashie/pull/249): SafeAssignment will now also protect hash-style assignments - [@jrochkind](https://github.com/jrochkind).
* [#251](https://github.com/intridea/hashie/pull/251): Added block support to indifferent access #fetch - [@jgraichen](https://github.com/jgraichen).
diff --git a/lib/hashie/dash.rb b/lib/hashie/dash.rb
index 849629f..cc20a93 100644
--- a/lib/hashie/dash.rb
+++ b/lib/hashie/dash.rb
@@ -96,7 +96,8 @@ module Hashie
self.class.defaults.each_pair do |prop, value|
self[prop] = begin
- value.dup
+ val = value.dup
+ val.is_a?(Proc) && val.arity > 0 ? val.call(self) : val
rescue TypeError
value
end
diff --git a/spec/hashie/dash_spec.rb b/spec/hashie/dash_spec.rb
index 1d44d5a..1de533f 100644
--- a/spec/hashie/dash_spec.rb
+++ b/spec/hashie/dash_spec.rb
@@ -46,6 +46,11 @@ class DeferredTest < Hashie::Dash
property :created_at, default: proc { Time.now }
end
+class DeferredWithSelfTest < Hashie::Dash
+ property :created_at, default: -> { Time.now }
+ property :updated_at, default: ->(test) { test.created_at }
+end
+
describe DashTest do
def property_required_error(property)
[ArgumentError, "The property '#{property}' is required for #{subject.class.name}."]
@@ -168,6 +173,14 @@ describe DashTest do
end
end
+ context 'reading from a deferred property based on context' do
+ it 'provides the current hash as context for evaluation' do
+ deferred = DeferredWithSelfTest.new
+ expect(deferred[:created_at].object_id).to eq deferred[:created_at].object_id
+ expect(deferred[:updated_at].object_id).to eq deferred[:created_at].object_id
+ end
+ end
+
describe '#new' do
it 'fails with non-existent properties' do
expect { described_class.new(bork: '') }.to raise_error(*no_property_error('bork'))