Why object_id changes after app initialization? - ruby-on-rails

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

Related

How to make logging in rails libs works like in models and controllers

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

How does Rails.application.configure block works without providing a variable name

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"

rails auto-loading and initializers

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.

How to use ActiveSupport::Configurable with Rails Engine

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

How do you create a configurable Ruby on Rails plugin?

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.

Resources