0

Using rails we rely on I18n.t and maybe more things that are configured in YAML files should be used with a similar method.

For example, I have a file with icecream prices

icecreams:
  water:
    strawberry: 5
    watermelon: 5
    peach: 6
  cream:
    chocolate: 7
    vanilla: 4
    lucuma: 8

How could I get the price of any ice cream like the way we use I18n?

For example: icecreams('cream.lucuma')

Lomefin
  • 1,173
  • 12
  • 43
  • Does this answer your question? [Rails 4 - Yaml configuration file](https://stackoverflow.com/questions/30865270/rails-4-yaml-configuration-file) – Eyeslandic Jul 07 '21 at 05:21

2 Answers2

1

A short an easy way should be to load the YAML file in an initializer

initializers/icecreams.rb

file_path = File.read(File.expand_path('./config/icreams.yml'))
ICECREAMS = YAML.safe_load(file_path, [], [], true).with_indifferent_access

def icecreams(path)
  dig_path = path.split('.').map(&:to_sym)
  ICECREAMS.dig(*dig_path)
end

Of course, I don't get the lazy version of I18n but its good enough.

Lomefin
  • 1,173
  • 12
  • 43
  • You can do all of that with the `config_for` method https://api.rubyonrails.org/classes/Rails/Application.html#method-i-config_for – Eyeslandic Jul 07 '21 at 05:22
1

Using the same code Lomefin shared above, I have added a small dynamic nature to it.

file_path = File.read(File.expand_path('./data.yaml'))
data = YAML.safe_load(file_path, [], [], true).with_indifferent_access

data.keys.each do |key|
  define_method(key) do |path|
    dig_path = path.split('.').map(&:to_sym)
    data[key].dig(*dig_path)
  end   
end

Assuming if the yaml file is extended further on the root node,

icecreams:
  water:
    strawberry: 5
    watermelon: 5
    peach: 6
  cream:
    chocolate: 7
    vanilla: 4
    lucuma: 8
languages:
  ruby:
    rails: 0
    sinatra: 1

Now you can access all those values from the yaml file.

2.5.1 :011 > languages('ruby.rails')
 => 0
2.5.1 :012 > languages('ruby.sinatra')
 => 1
2.5.1 :013 > icecreams('water.strawberry')
 => 5
2.5.1 :014 > icecreams('cream.chocolate')
 => 7