Reputation: 7664
To seed my database with airport names, I use application.yml to define a collection of airports:
AIRPORTS:
- name: "Charles de Gaulle"
city: "Paris"
country: "France"
- name: "Orly"
city: "Paris"
country: "France"
Using Rails Command (rails c) to test, I have:
2.0.0-p247 :001 > ENV['AIRPORTS']
=> "[{\"name\"=>\"Charles de Gaulle\", \"city\"=>\"Paris\", \"country\"=>\"France\"}, {\"name\"=>\"Orly\", \"city\"=>\"Paris\", \"country\"=>\"France\"}]"
which is a string! Then, when typing the following, I have an error:
2.0.0-p247 :002 > YAML.load(ENV['AIRPORTS'])
Psych::SyntaxError: (<unknown>): did not find expected ',' or '}' while parsing a flow mapping at line 1 column 2
from /Users/Hassen/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/psych.rb:205:in `parse'
from /Users/Hassen/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/psych.rb:205:in `parse_stream'
from /Users/Hassen/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/psych.rb:153:in `parse'
from /Users/Hassen/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/psych.rb:129:in `load'
from (irb):2
from /Users/Hassen/.rvm/gems/ruby-2.0.0-p247/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /Users/Hassen/.rvm/gems/ruby-2.0.0-p247/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /Users/Hassen/.rvm/gems/ruby-2.0.0-p247/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
What I'm expecting (what I want) is to have an array of objects, so I can seed my database with the following code:
YAML.load(ENV['AIRPORTS']).each do |airport|
AirPort.create airport
puts 'airport created: ' << airport.name
end
Thanks,
Upvotes: 1
Views: 1025
Reputation: 184
Using figaro gem
this would do the trick:
(eval ENV["AIRPORTS"]).each do |params|
Airport.create! params
puts "Airport created: #{params["name"]}"
I usually use a simple initializer load_config.rb
like:
YAML.load_file(Rails.root.join('config', 'application.yml'))['AIRPORTS'].each |params|
Airport.create! params
puts "Airport created #{params['name']}"
end
Upvotes: 1