Skip to content

Commit 04cc983

Browse files
author
PoTe
committed
Accept strings as keys for hash
1 parent f648302 commit 04cc983

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

lib/hashifiable.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def hashify(*args)
99

1010
args.each do |argument|
1111
case argument
12-
when Symbol
12+
when Symbol, String
1313
## Calls the specified method on the object and stores it
1414
## under the method name.
1515
hash_representation[argument] = self.send(argument)

spec/hashifiable_spec.rb

+12-2
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
require 'spec_helper'
22

3-
class TestUser < Struct.new(:id, :name, :credit_card, :secret_token)
3+
class TestUser < Struct.new(:id, :name, :credit_card, :secret_token, :quote)
44
extend Hashifiable
55
hashify :id,
66
:name,
7+
'quote',
8+
'random' => Proc.new { [1, 2, 3].sample },
79
:two_times_two => Proc.new { 2 * 2 },
810
:encrypted_token => Proc.new { secret_token + ' secret sauce' },
911
:lambdas_at_work => ->() { 2 * 2 }
1012
end
1113

1214
describe Hashifiable do
13-
let(:user) { TestUser.new(1, 'pote', '1123123241241', 'i2j34i2j34302843') }
15+
let(:user) { TestUser.new(1, 'pote', '1123123241241', 'i2j34i2j34302843', "It's bigger on the inside!") }
1416

1517
it 'should have a to_h method' do
1618
user.should respond_to(:to_h)
@@ -36,10 +38,18 @@ class TestUser < Struct.new(:id, :name, :credit_card, :secret_token)
3638
user.to_h[:id].should == 2
3739
end
3840

41+
it 'should include strings as well as symbols on the hash representation' do
42+
user.to_h['quote'].should == "It's bigger on the inside!"
43+
end
44+
3945
it 'should include procs in the hash representation' do
4046
user.to_h.keys.should include(:two_times_two)
4147
end
4248

49+
it 'should allow procs to have strings as keys' do
50+
user.to_h['random'].class.should == Fixnum
51+
end
52+
4353
it 'should return the output of the function and not a proc' do
4454
user.to_h[:two_times_two].should == 4
4555
end

0 commit comments

Comments
 (0)