Created
January 3, 2010 00:04
-
-
Save softcraft-development/267735 to your computer and use it in GitHub Desktop.
Add dynamic defaults to a Hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'shoulda' | |
class Hash | |
def with_defaults( default_blocks ) | |
new_hash = Hash.new do |hash, key| | |
value = default_blocks[key] | |
if value.respond_to? :call | |
value = value.call | |
end | |
value | |
end | |
new_hash.merge!(self) | |
end | |
end | |
class TestHashExtensions < Test::Unit::TestCase | |
def self.should_return_original_values | |
should "return the original value for a non-defaulted key" do | |
assert_equal "original value", subject[:original_key] | |
end | |
should "return the original value for a defaulted key" do | |
assert_equal "original value to be defaulted", subject[:to_be_defaulted] | |
end | |
should "return nil for a never-set key, as normal" do | |
assert_nil subject[:never_set] | |
end | |
end | |
context "A hash" do | |
setup do | |
@hash = {:original_key => "original value", | |
:to_be_defaulted => "original value to be defaulted" } | |
end | |
context "with a value-based default" do | |
subject do | |
@hash.with_defaults( { | |
:defaulted => "default value", | |
:to_be_defaulted => "default value for to_be_defaulted"} | |
) | |
end | |
should "return that default" do | |
assert_equal "default value", subject[:defaulted] | |
end | |
should_return_original_values | |
end | |
context "with a closure-based default" do | |
subject do | |
@hash.with_defaults( { | |
:defaulted => lambda { "value of default block" }, | |
:to_be_defaulted => lambda{"value of default block for to_be_defaulted"} | |
}) | |
end | |
should "return the value of the default block" do | |
assert_equal "value of default block", subject[:defaulted] | |
end | |
should_return_original_values | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment