yaml snippets

How to backup ActiveRecord model data to YAML with ar_fixtures

Tagged fixtures, backup, activerecord, rails, yaml  Languages ruby

First install the plugin:

script/plugin install http://github.com/mileszs/ar_fixtures/commits/master

Then dump data for all models with:

rake db:data:dump:all

There's a task for loading the data into the database, see rake -T for more information.

You can also do this without a plugin by using ActiveSupport::JSON and File.write to seed your database.

A simple configuration framework for storing a Rails app's configuration in YAML

Tagged ostruct, yaml, rails, configuration  Languages ruby

Create config/initializers/configuration.rb:

require 'ostruct'

# From https://www.ruby-forum.com/topic/137104
class NestedOstruct
  def self.to_ostruct(hash)
    mapping = {
      Hash => ->(s) { to_ostruct(s) },
      Array => ->(s) { s.collect { |i| i.is_a?(Hash) ? to_ostruct(i) : i } }
    OpenStruct.new {}.tap { |h| hash.each { |k, v| h[k] = (mapping[v.class] || ->(s) { s })[v] } }

config = YAML.load_file(Rails.root.join('config', 'application.yml'))[Rails.env].symbolize_keys
AppConfig = NestedOstruct.to_ostruct(config)

Create config/application.yml:

    api_key: xxx
    api_secret: xxx

Use it in your application: