noizeramp

Aleksey's programming, engineering and electronics log

YAML you may have never known

by Aleksey Gureev
23 October 2014

HTML and multiline strings

Storing HTML in YAML fields in a pretty way has never been as easy.

info: >
  <h1>Page title</h1>
  
  <p>Some paragraph text.</p>
    

NOTE: You’ll still need to tell Rails it’s safe HTML.

Arrays and hashes

This is useful when you keep the list of options. For example, for the <select> tags.

options:
  "yes": "Yes"
  "no":  "No"
  maybe: Maybe

NOTE: YAML interprets “yes” as true and “no” as false case-insensitively, that’s why we need to put them in quotes

And this is how you’d use them in Rails:

= select_tag :field, options_for_select(I18n.t('options').invert)

NOTE: We need to invert the Hash so that keys and values land where Rails expects them.

If you don’t care about key-value mapping, options can be stored as:

options: [ "Yes", "No", "Maybe" ]

or

options:
  - "Yes"
  - "No"
  - Maybe

NOTE: Quotes again.

Using this version in Rails is as easy, no inversion though:

= select_tag :field, options_for_select(I18n.t('options'))
tags: yaml - rails

Comments