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.
Related
Rails 6.1.4.1
I'm setting values from an initializer file and when I request a page, I find the object_id of the configuration changed (and the values lost) unless I do require 'my_library' in the initializer file. I don't understand why?
app/lib/feature_flags.rb:
class FeatureFlags
class Configuration
include ActiveSupport::Configurable
config_accessor(:my_key) { false }
end
class << self
def configuration
#configuration ||= Configuration.new
end
def configure
yield configuration
end
def enabled?(feature)
puts "#{__FILE__} FeatureFlags.configuration.object_id = #{FeatureFlags.configuration.object_id}"
configuration[feature]
end
end
end
config/initializers/feature_flags.rb:
# require 'feature_flag' # If I uncomment this line, the problem is solved
puts "#{__FILE__} FeatureFlags.configuration.object_id = #{FeatureFlags.configuration.object_id}"
FeatureFlags.configure do |config|
config.my_key = true
end
Output:
1. Run the rails server:
config/initializers/feature_flags.rb FeatureFlags.configuration.object_id = 14720
2. Request some page:
app/lib/feature_flags.rb FeatureFlags.configuration.object_id = 22880
My questions are:
Why do I need to require 'feature_flags' in the initializer for the object_id not to change? I thought Zeitwerk was taking care of this.
Is that how I'm supposed to do (to do it right)?
Thanks for your help!
I found my answer here: https://edgeguides.rubyonrails.org/autoloading_and_reloading_constants.html#use-case-1-during-boot-load-reloadable-code
Why is it not working: because FeatureFlags is a reloadable class, it is replaced by a new object uppon request.
How am I supposed to do it right: wrap my initialization code in a to_prepare block:
Rails.application.config.to_prepare do
FeatureFlags.configure do |config|
config.my_key = true
end
end
So far I always used "puts" to add custom logging infos to my code. But now it is kind of a pain. When I run rspec for exemple I'm not interested in all the verbose that I added with puts. So I installed the "logging and logging-rails gem" because its installation is real fast and satisfying.
It works well when I call logger from models and controller, but not when I'm using logger inside libraries. I get that error : NameError - undefined local variable or method `logger' for CustomLib:Class.
The easiest thing I succeeded is to call 'Rails.logger' instead of just 'logger'. But in that way in my logfile, the class referring to that line will be 'Rails' but I want 'CustomLib'. For models and controller the right classname is displayed without any intervention from myself.
# config/environnement/test.rb
# Set the logging destination(s)
config.log_to = %w[stdout]
config.log_level = :info
# Show the logging configuration on STDOUT
config.show_log_configuration = false
# lib/custom_lib.rb
class CustomLib
def initialize
Rails.logger.info 'foo'
end
end
When I will use or test my customlib class I'll get :
[2019-06-21T16:26:41] INFO Rails : foo
Instead I would like to see :
[2019-06-21T16:26:41] INFO CustomLib : foo
I'm a bit lost in all that log management in rails, I have no idea what to try next to reach that goal...
Edit
When I put a byebug just before the "logger.info 'foo' " line and enter into it via 'step', I got two different results if whether I'm in a model/controller or a custom lib.
# In custom lib, step enters this file "gems/logging-2.2.2/lib/logging/logger.rb"
# And Rails.logger returns an object like this one beloow
Logging::Logger:0x000055a2182f8f40
#name="Rails",
#parent=#<Logging::RootLogger:0x000055a2182e7ee8
#name="root",
#level=1>,
# In model/controller, step enters this file "gems/logging-rails-0.6.0/lib/logging/rails/mixin.rb"
# And Rails.logger returns an object like this one beloow
Logging::Logger:0x0000557aed75d7b8
#name="Controller",
#parent=#<Logging::RootLogger:0x0000557aedfcf630
#name="root",
#level=0>,
At the end I found a better way, I just need to include Logging.globally on top of the module where I want that behavior:
# lib/custom_lib.rb
class CustomLib
include Logging.globally
def initialize
logger.info 'foo'
end
end
The Rails in the log line is the progname of the logger. You could create a new logger that sets the progname to 'CustomLib'with (say) Rails.logger.clone.tap {|l| l.progname = 'CustomLib' }, but that isn't really the purpose of progname, which is to specify the name of the program, not the name of a class.
You could instead include the class name in the log line:
Rails.logger.info "[#{self.class}] - some message"
Or, for a bit more effort, you could define your own formatter. Here's one with a convenience method for wrapping an existing logger:
class ClassNameFormatter
def self.wrap_logger(klass, logger)
logger.clone.tap { |l| l.formatter = new(klass, logger.formatter) }
end
def initialize(klass, formatter=nil)
#klass = klass
#formatter = formatter ||= Logger::Formatter.new
end
def call(severity, timestamp, progname, msg)
#formatter.call severity, timestamp, progname, "[#{#klass.name}] - #{msg}"
end
end
To use it:
class CustomLib
def initialize
#logger = ClassNameFormatter.wrap_logger self.class, Rails.logger
end
def call
#logger.info 'test log please ignore'
end
end
Suppose I need to parse some configuration to instanciate some Service Singletons (that could be used with or without Rails).
A sample code example:
#services/my_service.rb
module MyService
#config = nil
def self.load_config(config)
#config = config
end
When using with Rail (or Capistrano, SInatra, etc.) I would use an initializer to boot up the service
#initializers/svc.rb
MyService.load_config(Rails.application.secrets.my_service.credentials)
But when used specifically with Rails, on every rails console restart!, this #config variable is cleared which is a problem...
Are there
after-reload! hooks that I could use to re-run the initializer ?
other types of variables that would be preserved during a restart!
that I could use here ?
You could define config method as:
def config
#config ||= Rails.application.secrets.my_service.credentials
end
And call this method instead of #config, so when the config variable is unset, it will be set again, otherwise it will return the value.
Seeing that people are still reading this, here is implementation I ended up with
# config/initializers/0_service_activation.rb
# Activation done at the end of file
module ServiceActivation
def self.with_reload
ActiveSupport::Reloader.to_prepare do
yield
end
end
module Slack
def self.service
::SlackConnector
end
def self.should_be_activated?
Utility.production? ||
Utility.staging? ||
(
Utility.development? &&
ENV['ENABLE_SLACK'] == 'true'
)
end
def self.activate
slack = service
slack.webhook = Rails.application.secrets.slack&.dig(:slack_webhooks)
Rails.application.secrets&.dig(:slack, :intercept_channel).try do |channel|
slack.intercept_channel = channel if channel.present?
end
slack.activate
slack
end
end
[
ServiceActivation::Intercom,
ServiceActivation::Slack,
ServiceActivation::Google
] .each do |activator|
ServiceActivation.with_reload do
activator.activate if activator.should_be_activated?
activator.service.status_report
end
end
I am not showing my connector class SlackConnector, but basically you can probably guess the interface from the way it is called. You need to set the webhook url, and do other stuff. The implementation is decoupled, so it's possible to use the same SlackConnector in Rails and in Capistrano for deployment, so it's basically in the lib/ folder
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