Created
January 27, 2010 06:43
-
-
Save amatsuda/287602 to your computer and use it in GitHub Desktop.
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
module RegexpableHash | |
def kakko_with_regexp(key) | |
if val = kakko_without_regexp(key) | |
return val | |
end | |
if matched_key = self.keys.detect {|k| Regexp.new("\\A#{k}\\Z") =~ key.to_s} | |
if (val = kakko_without_regexp(matched_key)).is_a? String | |
# 0が含まれてるけどまぁいっか的な。 | |
Regexp.last_match.to_a.each_with_index do |m, i| | |
val.gsub! "$#{i}", m | |
end | |
end | |
val | |
end | |
end | |
def self.extended(base) | |
base.instance_eval do | |
alias :kakko_without_regexp :[] | |
alias :[] :kakko_with_regexp | |
end | |
end | |
end | |
h1 = Hash.new | |
h1[:hoge] = 'ほげ' | |
h1[:'user_(\d)'] = 'ユーザー$1' | |
h1.extend RegexpableHash | |
puts h1[:hoge] == 'ほげ' | |
puts h1[:user_1] == 'ユーザー1' | |
puts h1[:user_2] == 'ユーザー2' | |
# RailsのI18nのbackendで使用する場合 | |
def xtend(hash) | |
hash.extend RegexpableHash | |
hash.values.each {|h| xtend(h) if h.is_a? Hash} | |
hash | |
end | |
I18n.backend.send :init_translations | |
t = I18n.backend.send :translations | |
xtend t | |
t[:ja][:activerecord][:models][:'banner_(\d+)'] = 'バナー$1' | |
I18n.t 'activerecord.models.banner_838861' | |
#=> "バナー838861" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment