views:

336

answers:

2

I have a rails helper in my application_helper.rb file that looks like this:

def external_link(name)
    url = external_links[name]
    if url.blank?
        Rails.logger.error "No URL defined for external link [#{name}]!"
        return "[URL undefined]"
    end
    return url
end

The 'external_links' variable is a hash that should be sourced from an external file. The file can be something as simple as a ruby hash or a simple YML config.

Maybe I'm missing something - I thought I'd be able to define the hash in ruby syntax in an external file and 'require' it from environment.rb, but that doesn't expose the hash variable in the helper.

How can I externalise a ruby hash such that it will be "in scope" in an application helper method?

+1  A: 

Use a basic YML file as you indicated and then load it up via:

config = YAML::load_file(RAILS_ROOT+'/config/external_urls.yml')

Then you can access it via the "config" object accordingly. If the file doesnt change between requests you could cache this file load for later use (so its not opened and parsed on each use), but thats a performance optimization and not critical for a proof-of-concept.

Cody Caughlan
+1  A: 

I use Application Config, which lets me set up RAILS_ROOT/config/application_config.yml like this:

  development: &defaults
    items_per_page: 25
    secure_with_basic_auth: false
    base_url: development.com
  test:
    <<: *defaults
    base_url: test.com
  production:
    <<: *defaults
    base_url: production.com

Then reference them like this:

  class FooController < ApplicationController
    def index
      @base_url = property(:base_url)
    end
  end

There's also the AppConfig plugin, which looks even better, but I haven't tried that yet.

Chris Doggett
I didn't like the look of the AppConfig API but the simple ApplicationConfig plugin seems great, thanks!
Lee