Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Can you put Ruby code in a YAML config file?

Tags:

ruby

yaml

I would like to do something like this in my amazon_s3.yml config file:

access_key_id: ENV['S3_KEY'] secret_access_key: ENV['S3_SECRET'] 

...but I know this isn't working. Not sure if it is even possible, but can you put Ruby code in a YAML file?

like image 543
Andrew Avatar asked Jul 18 '10 22:07

Andrew


People also ask

How do I access values from YAML file?

Next, we need to load the YAML file using the safe_load function available in the PyYAML package. From the above code, we start by importing the yaml package. We then create a main function (any name works) and set the logic for reading the yaml file. Once the file is open and read, we call the main function.

What is Ruby config?

MSpec provides a simple way to specify configuration options for the runner scripts by putting them in a file rather than using command line switches. The config files are simply Ruby files. There may be zero or more config files. The runner scripts attempt to load several config files by default.

How do I open a YAML file in Linux?

How to open a YAML file. You can open a YAML file in any text editor, such as Microsoft Notepad (Windows) or Apple TextEdit (Mac). However, if you intend to edit a YAML file, you should open it using a source code editor, such as NotePad++ (Windows) or GitHub Atom (cross-platform).


2 Answers

Not normally / directly. I say this because in order to use ruby results you need to use something like ERB first before loading the file. In terms of code, you need to go from something like:

loaded_data = YAML.load_file("my-file.yml") 

Or even

loaded_data = YAML.load(File.read("my-file.yml")) 

To:

loaded_data = YAML.load(ERB.new(File.read("my-file.yml")).result) 

In this specific case, you would have to look at what is loading the file - in some cases, it may already be designed to load it straight out of the environment or you may need to either:

  1. Monkey Patch the code
  2. Fork + Use your custom version.

Since there are a few plugins that use amazon_s3.yml, It might be worth posting which library you are using that uses it - alternatively, I believe from a quick google that the AWS library lets you define AMAZON_ACCESS_KEY_ID and AMAZON_SECRET_ACCESS_KEY as env vars and it will pick them up out of the box.

like image 165
Sutto Avatar answered Oct 06 '22 00:10

Sutto


You can if it is interpreted through ERB, in which case it acts like an ERB view and Ruby code goes between <% and %>

Try:

access_key_id: <%= ENV['S3_KEY'] %> secret_access_key: <%= ENV['S3_SECRET'] %> 

... and see if it works

like image 33
Mike Tunnicliffe Avatar answered Oct 06 '22 00:10

Mike Tunnicliffe