Skip to content

Commit 94d37d0

Browse files
committed
add hash interpolation to gibberish
1 parent 9ea0649 commit 94d37d0

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

‎README‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,11 @@ Notice we don't use hashes (#) like normal Ruby interpolation. Also, the names
4444
in the brackets don't really mean much. Interpolation is done in order -- the first argument replaces
4545
the first variable in brackets, the second the second, etc.
4646

47+
Interpolation can also be done via hash:
48+
49+
>> "{name} is from {place}"[:hey_place, { :place => 'Gotham City', :name => 'Batman' }]
50+
=> "Batman is from Gotham City"
51+
4752
This of course works with your translations:
4853

4954
$ cat lang/es.yml

‎lib/gibberish/localize.rb‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,21 @@ def load_languages!
5959

6060
private
6161
def interpolate_string(string, *args)
62-
string.gsub(/\{\w+\}/) { args.shift }
62+
if args.last.is_a? Hash
63+
interpolate_with_hash(string, args.last)
64+
else
65+
interpolate_with_strings(string, args)
66+
end
67+
end
68+
69+
def interpolate_with_hash(string, hash)
70+
hash.inject(string) do |target, (search, replace)|
71+
target.sub("{#{search}}", replace)
72+
end
73+
end
74+
75+
def interpolate_with_strings(string, strings)
76+
string.gsub(/\{\w+\}/) { strings.shift }
6377
end
6478

6579
def language_files

‎test/gibberish_test.rb‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,14 @@
134134
'{computer} omg?'[:puter, 'mac'].should.equal "mac omg?"
135135
end
136136

137+
specify "should interpolate based on key if passed a hash" do
138+
'Hi, {user} of {place}'[:hi_there, { :place => 'france', :user => 'chris' }].should.equal "Hi, chris of france"
139+
140+
bands = { 'other_bad_band' => 'Deputy', :good_band => 'Word Picture', 'bad_band' => 'Dagger' }
141+
answer = 'Well, Dagger sucks and so does Deputy, but Word Picture is pretty rad.'
142+
'Well, {bad_band} sucks and so does {other_bad_band}, but {good_band} is pretty rad.'[:snobbish, bands].should.equal answer
143+
end
144+
137145
specify "should not affect existing string methods" do
138146
string = "chris"
139147
answer = 'ch'

0 commit comments

Comments
 (0)