Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created July 8, 2009 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakajima/afe18b5713b036e2324f to your computer and use it in GitHub Desktop.
Save nakajima/afe18b5713b036e2324f to your computer and use it in GitHub Desktop.
HashyThing = Struct.new(:name, :age) do
def initialize(attributes={})
super
attributes.each { |key, val| send("#{key}=", val) }
yield self if block_given?
end
def to_hash
members.inject({}) do |res, key|
res[key] = send(key)
res
end
end
end
require 'test/unit'
class HashyThingTest < Test::Unit::TestCase
def test_takes_a_hash
thing = HashyThing.new(:name => 'Pat', :age => 23)
assert_equal 23, thing.age
assert_equal 'Pat', thing.name
end
def test_takes_a_block
thing = HashyThing.new do |obj|
obj.name = 'Pat'
obj.age = 23
end
assert_equal 23, thing.age
assert_equal 'Pat', thing.name
end
def test_to_hash
attrs = { :name => 'Pat', :age => 23 }
thing = HashyThing.new(attrs)
attrs.each do |key, val|
assert_equal val, thing.to_hash[key.to_s]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment