Today I Learned

hashrocket A Hashrocket project

Importing Multiline Strings in Rails Config

Say I have a multiline string for an environment variable

MY_VAR="hi
bye"

If I try to import that in a Rails config yml file, I'm going to have a bad time.

config:
  my_value: <%= ENV.fetch("MY_VAR") %>

If this config file is autoloaded, rails is going to blow up on startup:

YAML syntax error occurred while parsing config.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Error: (<unknown>): could not find expected ':' while scanning a simple key at line 15 column 1 (Psych::SyntaxError)

This is happening because the ERB output is not writing the line breaks in a way that Psych (ruby YAML parser) knows how to handle. We can use String#dump to return the quoted version of the string to make Psych happy.

"hi
bye".dump

=> "\"hi\\nbye\""

So the resulting config would look like so:

config:
  my_value: <%= ENV.fetch("MY_VAR").dump %>

And then our app can start and in console:

Rails.configuration.config.my_value

=> "hi\nbye"
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.