Skip to content

Instantly share code, notes, and snippets.

@deepak
Created November 17, 2011 12:14
Show Gist options
  • Select an option

  • Save deepak/1373010 to your computer and use it in GitHub Desktop.

Select an option

Save deepak/1373010 to your computer and use it in GitHub Desktop.
rails custom config
FooBar::Application.config.mine = OpenStruct.new({})
FooBar::Application.config.mine.omniauth_config = {:facebook => { :app_id => 123 } }
# how do i access the config in my controller
# i can do FooBar::Application.config.mine but that is too verbose
@deepak
Copy link
Copy Markdown
Author

deepak commented Nov 17, 2011

setting the config in a variable for shorter access

class ApplicationController < ActionController::Base
  before_filter :set_config

  def set_config
   @facebook_config = Rails.configuration.mine.omniauth_config[:facebook]
  end
end

but the problem here is that we have to allocate another string/hash on every request even when it does not change.
if the config does not change, can just use a constant. can reassign it, but it will be semantically dirty and ruby will give a warning

module FacebookConfig
  config = Rails.configuration.app.omniauth_config[:facebook]
  APP_ID = config[:app_id]
end

Also using Rails.configuration as otherwise will have to remember the name of the app like FooBar::Application.config

storing & sharing config is a pain.
-> if it does not change use a constant. semantically correct and will utilize less memory and less GC cycles
-> if it can change per-request, use instance variable in the controller and pass the values to the model when ever needed
we can just reassign the constant. but it is semantically dirty and ruby will throw a warning
-> sometimes we will just have to assign a thread local variable. useful in case controller needs to set a variable which needs to be used in the model in a filter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment