Blankman
Blankman

Reputation: 267160

Creating a class that wraps my config.yml file, and using it in my rake files

This is a non-rails app, just a simple ruby script that uses rake etc. to automate some things.

My folder layout is this:

/scripts/Rakefile
/scripts/config/config.yml
/scripts/tasks/*.rake (various rake files with namespaces to organize them)
/scripts/lib/settings.rb

Now I want to create a Settings class that will load the config yaml file, and then expose properties/methods for the contents of the yaml file.

The yaml file has separate sections for development and production.

development:
    scripts_path: '/dev/mygit/app1/scripts/'
production:
    scripts_path: '/var/lib/app1/scripts/'

My rakefile so far looks like:

$LOAD_PATH.unshift File.expand_path('..', __FILE__)

#imports
require 'fileutils'
require 'rubygems'
require 'active_record'
require 'yaml'
require 'logger'

require 'ar/models'
require 'lib/app1'

env = ENV['ENV'] || 'development'
config = YAML::load(File.open('config/config.yml'))[env]

Dir.glob('tasks/*.rake').each { |r| import r }

I need help with the Settings.rb file, is this right?

module App1
  class Settings
    def initialize(config_path, env)
      config = YAML.load(File.open(config_path))
    end

    def scripts_path
    end

  end
end

How can I pass in the env, and then read the correct value from the config for each method like scripts_path etc?

Now suppose each *.rake file needs to reference my Settings.rb file somehow (to get the config related information). How should I do this? Since my settings needs the path of the config.yml file, do I have to do this in each rake file?

Update Sorry, this isn't a Rails app, just some ruby scripts.

Upvotes: 2

Views: 1728

Answers (2)

Matthew Rudy
Matthew Rudy

Reputation: 16834

I would do it quite simple. You don't need a complex solution.

require 'ostruct'
require 'yaml'

MY_ENV = ENV['ENV'] || 'development'
CONFIG = OpenStruct.new(YAML.load_file("config/config.yml")[MY_ENV])

Stick this at the top of your rakefile and CONFIG will be available in all rake tasks.

Just call CONFIG.scripts_path

Upvotes: 3

Matthew Rudy
Matthew Rudy

Reputation: 16834

Inside my applications I do something of this sort.

# config/application.yml

development:
  some_variable: a string

production:
  some_variable: a different string

Then in application.rb I load it up.

# config/application.rb

module MyApp

  def self.config
    @config ||= OpenStruct.new(YAML.load_file("config/application.yml")[Rails.env.to_s])
  end

  class Application < Rails::Application
    ...

In this case, anywhere the environment is loaded I can say

MyApp.config.some_variable

To get access to this inside a rake task, I just need to include environment

task :something => :environment do
  MyApp.config.some_variable
  # do something with it
end

Upvotes: 1

Related Questions