kriysna
kriysna

Reputation: 6168

Passing variables in yaml file

I love using i18n and yml. I want my own yaml file that do similar thing. That is accessing variable in yaml file. Something like this

name:
  address: "%{city} %{street}"

add variable could pass something like some_method('name.address', :city => 'my city', :street => 'my street')

In i18n we can do

en:
 message:
  welcome: "Hello %{username}"

To call this we can use t("message.welcome", :username => 'admin')

How can I implement it?

Upvotes: 5

Views: 8595

Answers (1)

shingara
shingara

Reputation: 46914

It's replace after the call. By example.

Yaml.load_file('locale/en.yml')['en']['message']['welcome'].gsub('%{username}', username)

So in method it can be :

  def t(key, changes)
    result = yaml_locale['en']
    key.split('.').each |k|
      result = result[k]
    end
    changes.each_keys do |k|
      result.gsub!("%{#{k}}%", changes[k])
    end
    result
  end

Refactor it a little after but the idea is like that.

The original method is here : https://github.com/svenfuchs/i18n/blob/master/lib/i18n.rb#L143 Manage a lot of think I don't :)

Upvotes: 4

Related Questions