Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to DRY up yaml?

I am using Rails' 4.1.4 YAML locale files to store some translations, for example:

en:
  words:
    en:
      passport: "passport"
      ticket: "ticket"
      train: "train"
de:
  words:
    en:
      passport: "passport"
      ticket: "ticket"
      train: "train"

With this I can use t("words.#{to_language}.train") to return train for a German user (I18n.locale == :de) who has chosen english as his to_language.

My question is: is there any way I can not repeat myself and have something like code below?

en OR de:
  words:
    en:
      passport: "passport"
      ticket: "ticket"
      train: "train"

Perhaps I can assign all the content of words to a variable and then just do:

en:
  all_words
de:
  all_words

Thanks

like image 681
Epigene Avatar asked Dec 15 '14 09:12

Epigene


People also ask

How do I fix YAML error?

To fix errors in . yml files, you will need to use a YAML Parser. Paste your . yml configuration file into the YAML Parser - the file with the error is most likely the file you edited last.

How do I fix indentation error in YAML?

The error text states this is an indentation error, and you fix it by adding an additional two spaces before each dash ( - ) character. If you don't know why those are errors, read my YAML for Ansible article.

Does order matter in YAML file?

The structure of a YAML file is a map or a list. Maps allow you to associate key-value pairs. Each key must be unique, and the order doesn't matter.

Is YAML hard to learn?

YAML is an easy, expressive, data-oriented language that distinguishes itself from document markup languages. YAML Ain't a Markup Language (YAML), and as configuration formats go, it's easy on the eyes.


1 Answers

Yes, YAML allows you to repeat nodes via reference. In particular, Ruby's YAML has something nonstandard called a "merge key", which will be useful in your particular situation.

For example, if you have, say:

base_fruits: &default # Alias the keys here into `default`.
  apple: one
  banana: two

then you can do

fruit_basket_one:
  <<: *default        # Include all the keys from the alias `default`.
  coconut: three      # Add another key too.

fruit_basket_two:
  <<: *default
  durian: five
  pear: six

So you can do something like:

en:
  words:
    en: &all_en_words
      passport: "passport"
      ticket: "ticket"
      train: "train"

de:
  words:
    en:
      <<: *all_en_words
      custom_word: "custom translation"

I would say that this probably isn't the right way to go about it, though. If a de user wants en translations, then they should just use en. Otherwise you will need an N^2 mapping for every pair of (actual language, desired language), instead of just a list of N translations, which is far easier to maintain.

like image 180
John Feminella Avatar answered Sep 24 '22 11:09

John Feminella