In a Rails4 project I am working on,
inside the development.rb file (and in the others enviroments),
inside the configure block:
Rails.application.configure do
...
config.foo = 'foo'
end
I can use whatever setter I want, like config.foo=
(I suppose some dynamic code under the hood)
what's the purpouse of that and how does it work ? I did't not find any documentation about it.
Thanks for any help to understant it.
The following code in rails/railties/lib/rails/application/configuration.rb file on the rails code base sets what the valid config options are:
attr_accessor :allow_concurrency, :asset_host, :assets, :autoflush_log,
:cache_classes, :cache_store, :consider_all_requests_local, :console,
:eager_load, :exceptions_app, :file_watcher, :filter_parameters,
:force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
:railties_order, :relative_url_root, :secret_key_base, :secret_token :serve_static_files, :ssl_options, :static_cache_control, :session_options,
:time_zone, :reload_classes_only_on_change,
:beginning_of_week, :filter_redirect, :x
attr_writer :log_level
attr_reader :encoding
Rails uses any of the settings mentioned above, and simply ignores the rest.
The dynamic code under the hood is also in the same file
def method_missing(method, *args)
if method =~ /=$/
#configurations[$`.to_sym] = args.first
else
#configurations.fetch(method) {
#configurations[method] = ActiveSupport::OrderedOptions.new
}
end
end
Related
In Rails, it's common to see a pattern like this (in config/environments/development.rb for example):
Rails.application.configure do
config.some_option = some_value
end
I was intrigued by this idiom since I was recently researching how these configure blocks work and ended up discovering this very similar pattern, where the configure method initializes an (generally memoized) instance of a configuration Class (that has the accessors for the configuration options) and yield that instance object to the block. Something like this:
module Clearance
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration)
end
class Configuration
attr_accessor :mailer_sender
def initialize
#mailer_sender = 'donotreply#example.com'
end
end
end
That's why Clearance.configure {|config| config.mailer_sender = 'something'} works, because it's yielding that instance of Configuration class to the block variable config.
But the way Rails does it, there's no variable being passed to that block. There's no Rails.application.configure do |config| so the block can change the configuration object accessors. I thought config would be undefined inside that block, but it isn't.
Tried looking at rails source code and I suspect it has to do with the configurable module, but I couldn't 100% understand the code I found there.
It seems the Configurable module isn't used by the actual Rails railtie.
https://github.com/rails/rails/blob/5ccdd0bb6d1262a670645ddf3a9e334be4545dac/railties/lib/rails/railtie.rb#L170
I don't claim to understand it's usage fully, but apparently the delegate method used in Railtie class
delegate :config, to: :instance
adds a config attribute pointing to an instance of Rails::Application::Configuration - the one which we later access through Rails.application.config.
https://apidock.com/rails/Module/delegate
It uses instance_eval (or class_eval which does essentially the same) to evaluate the block in the context of a specified object. Within the block, that object becomes the implicit receiver (i.e. self).
For example, using your code:
module Clearance
class << self
attr_accessor :configuration
end
def self.configure(&block)
self.configuration ||= Configuration.new
configuration.instance_eval(&block)
end
class Configuration
attr_accessor :mailer_sender
def initialize
#mailer_sender = 'donotreply#example.com'
end
end
end
Clearance.configure { self.mailer_sender = 'something' }
Clearance.configuration.mailer_sender #=> "something"
I have a simple module with a basic configuration pattern and API connect method. I am configuring this module in initializer.
services/tasks_manager.rb:
module TasksManager
class << self
attr_reader :client
end
def self.configuration
#configuration ||= Configuration.new
end
def self.configure
yield configuration
end
def self.connect
#client ||= SecretAPI::Client.new do |config|
config.url = configuration.url
config.token = configuration.token
config.username = configuration.username
config.password = configuration.password
end
self
end
#.
#.
# other stuff
#.
#.
class Configuration
attr_accessor :url
attr_accessor :username
attr_accessor :token
attr_accessor :password
end
end
config/initializers/tasks_manger.rb
TasksManager.configure do |config|
config.url = "a..."
config.username = "b..."
config.password = "c..."
config.token = "d..."
end
When I start rails app all is working fine I can use TasksManager by different objects and it is using configuration that has been set up in initializer. But...
When I make a small change to the services/tasks_manager.rb file, like commenting something out or adding new method to it. I am required to restart the rails app. TasksManager.configuration is empty at this stage. It looks like making a changes to the file forces creation of the new module and initializer is not loaded.
It might be a normal behaviour but it took me a while to figure it out and I was thinking that maybe someone will be able to explain it to me.
I am using rails 4.2 with spring(is it why?).
you can put your initialization-code into a ActionDispatch::Callbacks.to_prepare {} block. that will evaluate it whenever rails reloads classes.
I want to give my rails engine gem a proper configuration possibilities.
Something that looks like this in initializers/my_gem.rb (link to the current initializer):
MyGem.configure do |config|
config.awesome_var = true
# config.param_name = :page
end
So I've looked around for any clues in other gems and the best I cloud find was this kaminari/config.rb.
But it looks so hacky that I think there must be a better way.
The source file for ActiveSupport::Configurable got decent documentation:
https://github.com/rails/rails/blob/master/activesupport/lib/active_support/configurable.rb
I like to put the configuration into it's own class within the engine (like kaminari does):
class MyGem
def self.configuration
#configuration ||= Configuration.new
end
def self.configure
yield configuration
end
end
class MyGem::Configuration
include ActiveSupport::Configurable
config_accessor(:foo) { "use a block to set default value" }
config_accessor(:bar) # no default (nil)
end
Now I can configure the engine with this API:
MyGem.configure do |config|
config.bar = 'baz'
end
And access the configuration with
MyGem.configuration.bar
try this out
I hope this is simple and clear.
Example Code
In a Rails 3.2 app I need to access url_helpers in a lib file. I'm using
Rails.application.routes.url_helpers.model_url(model)
but I'm getting
ArgumentError (Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true):
I've found a few things written about this, but nothing that really explains how to solve this for multiple environments.
i.e. I assume I need to add something to my development.rb and production.rb files, but what?
Closest I've seen to an answer suggested using config.action_mailer.default_url_option, but this does not work outside of action mailer.
What is the correct way to set the host for multiple environments?
This is a problem that I keep running into and has bugged me for a while.
I know many will say it goes against the MVC architecture to access url_helpers in models and modules, but there are times—such as when interfacing with an external API—where it does make sense.
After much searching I've found an answer!
#lib/routing.rb
module Routing
extend ActiveSupport::Concern
include Rails.application.routes.url_helpers
included do
def default_url_options
ActionMailer::Base.default_url_options
end
end
end
#lib/url_generator.rb
class UrlGenerator
include Routing
end
I can now call the following in any model, module, class, console, etc
UrlGenerator.new.models_url
Result!
A slight improvement (at least for me) on Andy's lovely answer
module UrlHelpers
extend ActiveSupport::Concern
class Base
include Rails.application.routes.url_helpers
def default_url_options
ActionMailer::Base.default_url_options
end
end
def url_helpers
#url_helpers ||= UrlHelpers::Base.new
end
def self.method_missing method, *args, &block
#url_helpers ||= UrlHelpers::Base.new
if #url_helpers.respond_to?(method)
#url_helpers.send(method, *args, &block)
else
super method, *args, &block
end
end
end
and the way you use it is:
include UrlHelpers
url_helpers.posts_url # returns https://blabla.com/posts
or simply
UrlHelpers.posts_url # returns https://blabla.com/posts
Thank you Andy! +1
Use this string in any module controller to get application URL-helpers works in any view or controller.
include Rails.application.routes.url_helpers
Please note, some internal module url-helpers should be namespaced.
Example:
root application
routes.rb
Rails.application.routes.draw do
get 'action' => "contr#action", :as => 'welcome'
mount Eb::Core::Engine => "/" , :as => 'eb'
end
Url helpers in module Eb:
users_path
Add include Rails.application.routes.url_helpers in controller contr
So after that helper should be
eb.users_path
So inside Eb module you can use welcome_path same as in root application!
Not sure if this works in Rails 3.2, but in later versions setting default url options for the routes can be done directly on the routes instance.
So for example, to set the same options as for ActionMailer:
Rails.application.routes.default_url_options = ActionMailer::Base.default_url_options
i am trying to create my first rails plugin, and i want it to be configurable, that is to say, i want to be able to set a variable in the environment.rb file or something.
UPDATE: i'm trying to do something like what's done here: http://soakedandsoaped.com/articles/read/exception-notifier-ruby-on-rails-plugin. i have tried mimicking their code, but i can't get it working.
i have the plugin working with the value hard-coded, but everything i have tried so far for making it configurable hasn't worked.
Here's some of the code:
#vendor/plugin/markup/lib/markup_helper.rb
module MarkupHelper
def stylesheet_cache_link_tag(*sources)
cache = assests_cache_dir ? assests_cache_dir : ""
options = sources.extract_options!.stringify_keys
cached_name = options.delete("cached_name")
stylesheet_link_tag(sources, :cache=> File.join(cache, cached_name))
end
def javascript_cache_include_tag(*sources)
cache = assests_cache_dir ? assests_cache_dir : ""
options = sources.extract_options!.stringify_keys
cached_name = options.delete("cached_name")
javascript_include_tag(sources, :cache=> File.join(cache, cached_name))
end
end
#something like the following in config/environment.rb or probably config/environments/production.rb
MarkupConfig.assests_cache_dir = "cache"
i want assests_cache_dir to default to "cache" but be able to set in an environment config file. i have googled a long time on this, and can't find anything discussing this. How can i accomplish this?
module MarkupHelper
mattr_accessor :assets_cache_dir
self.assets_cache_dir = "cache"
def assets_cache_dir
MarkupHelper.assets_cache_dir
end
end
Then in environment.rb (or development.rb/test.rb/production.rb if you want different values for each environment):
MarkupHelper.assets_cache_dir = "my-value"
Although the approach used by tomafro is quite easy to use, another approach is to use a database.yml-style configuration file that can be split according to environments:
module MyPlugin
class Configuration
# == Constants ==========================================================
CONFIG_FILES = [
"#{RAILS_ROOT}/config/myplugin.yml",
"#{RAILS_ROOT}/config/myplugin.yaml"
].freeze
DEFAULT_CONFIGURATION = {
:url => DEFAULT_HOSTNAME
}.freeze
# == Class Methods ======================================================
# :nodoc:
def self.config_file_found
CONFIG_FILES.find do |path|
File.exist?(path)
end
end
# Returns the default path to the configuration file
def self.default_path
config_file_found or CONFIG_FILES.first
end
# == Instance Methods ===================================================
# Creates a new MyPlugin::Configuration instance by reading from the
# configuration file.
# +env+ The Rails environment to load
def initialize(env)
config_file = self.class.config_file_found
#env_config = DEFAULT_CONFIGURATION
if (#config = (config_file and YAML.load(File.open(config_file))))
[ #config['defaults'], #config[env] ].each do |options|
if (options)
#env_config = #env_config.merge(options.symbolize_keys)
end
end
end
end
# Will return +true+ if a configuration file was found and loaded, or
# +false+ otherwise.
def exists?
#env_config != DEFAULT_CONFIGURATION
end
# Returns a particular configuration option.
def [](key)
#env_config[key.to_sym]
end
end
def self.config
#config ||= Configuration.new(Rails.env)
end
end
You would use this as:
settting = MyPlugin.config[:param_name]
You can also write utility methods to fetch particular values, or use OpenStruct instead of a configuration Hash. This is posted merely as an example of another design pattern.