I'm trying to simplify our configuration by creating small configuration classes that can be included in our application.rb.
lib/logging.rb
class << Logging
def configure(config)
# ... configure logging stuff
end
end
application.rb
require 'lib'
module MyApp
class Application < Rails::Application
Logging.configure(config)
end
end
The problem is if I don't use require "lib" then I get an Undefined Constant Logging error. But if I try to require it I get:
bin/rails:6: warning: already initialized constant APP_PATH
/opt/qtip/bin/rails:6: warning: previous definition of APP_PATH was here
The only way I've been able to get it to work is by doing this which is very limiting.
config.autoload_paths = %w(lib)
config.after_initialize do
::Logging.configure(config)
end
You have wrong class declaration.
Instead
class << Logging
you should use
class Logging
class << self
def configure(config)
end
end
end
Related
I have some code i've inherited and am in the process of upgrading it to Rails 3.1. I'm suuuuper close to done but I got a bug.
In Rails Console I run User.first and I get this error
undefined local variable or method `acts_as_userstamp' for #<Class:0x000000046bef50>
Now acts_as_userstamp is a method located on line two inside my User model
class User < ActiveRecord::Base
#TODO /lib is not loading??? or is it??? why this method not work in browser?
acts_as_userstamp
And is defined in a file called app/lib/model_modifications.rb.
Now I recently discovered that my app/lib folder was not being autoloaded in my application.rb file and I think that's been fixed...or has it? Is this file correct? Or no?
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# evil outdated soap middleware, TODO: kill it with fire
# Does this have to be loaded BEFORE the first line???
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', "vendor", "soap4r"))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', "vendor", "plugins", "soap4r-middleware", "lib"))
# evil outdated soap middleware, TODO: kill it with fire
require 'soap4r-middleware'
require File.join(File.dirname(__FILE__), '..', 'app', 'lib', 'soap.rb')
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require *Rails.groups(:assets => %w(development test))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module MyappDev
class Application < Rails::Application
# startup the lib directory goodies <-- IS THIS CORRECT???
# config.autoload_paths << "#{Rails.root}/lib"
# config.autoload_paths += %W( lib/ )
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
config.middleware.use MyAPIMiddleware
end
end
I'm trying to debug this file as I post this now. Here is a peak at it's internal structure...(i've just included the overall structure for the sake of brevity)
app/lib/model_modificatons.rb
class Bignum
...
end
class Fixnum
...
end
class ProcessorDaemon
...
end
module ActiveRecord
module UserMonitor
...
end
module MyLogger
...
end
end
class Object
...
end
class Struct
...
end
class String
...
end
class Fixnum
...
end
class OpenStruct
...
end
class ActiveRecord::Base
def self.visible_columns
...
end
...
def self.acts_as_userstamp
logger.info "HI fonso - acts_as_userstamp is called"
include ActiveRecord::UserMonitor
end
...
protected
def self.range_math(*ranges)
...
end
end
class Array
...
end
class DB
...
end
If you can spot a problem with the overall structure or anywhere else please let me know.
So why is this method not found? I'm trying to debug it as I'm posting this and I'm getting nothing.
I suspect the file app/lib/model_modifications.rb is not being loading. That nothing in the /lib directory is being loaded..but how do I confirm this?
Thank you for reading this far, I hope I've not rambled on too much.
autoload_path configuration does not load all the given files on the boot but defines folders where rails will be searching for defined constants.
When your application is loaded, most of the constants in your application are not there. Rails have a "clever" way of delaying loading the files by using a constant_missing method on Module. Basically, when Ruby encounters a constant in the code and fails to resolve it, it executes said method. THe sntandard implementation of this method is to raise UndefinedConstant exception, but rails overrides it to search all of its autoload_paths for a file with a name matching the missing constant, require it and then check again if the missing constant is now present.
So, in your code everything works as expected and you need to load this extension file manually. If you want to have some code that executes on the application boot, put your file within config/initializers folder.
Aside: Try avoiding monkey patching whenever possible. It might be looking clever, but adding more methods to already overpopulated classes will not make them easier to use.
We are writing a gem that includes multiple common gems for a couple of our shared apps. We want to be able to have a config in application.rb or enviroment.rb/*rb something like config.fruit_chain.enable_transport = true from the consuming app to conditionally require a gem and it's initializer dynamically. But the initializer from common gem does not run after require in a railtie. I wondered if there is a better way to do this
fruit_store/config/application.rb . (consuming app)
module FruitStore
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
config.fruit_chain.enable_transport = true
end
end
fruit_chain/lib/fruit_chain.rb (Our gem)
require analytic
- require transport <----- removed this so it dose not autoload
require marketing
...
module FruitChain
end
fruit_chain/lib/fruit_chain/rails/railtie.rb
module FruitChain
module Rails
class Railtie < ::Rails::Railtie
config.fruit_chain = ActiveSupport::OrderedOptions.new
config.fruit_chain.enable_transport = false
config.before_initialize do |app|
if app.config.fruit_chain.enable_transport
Kernel.require 'transport' <--- this require the gem correct and load it up
app.initializers.find{
|a| a.name === 'transport.configure'
}.run <--- transport.configure initializer doesn't kick off
end
end
end
end
end
transport/lib/transport.rb . (Dependent common gem)
require transport/rails/railtie
...
module Transport
end
transport/lib/transport/rails/railtie.rb
module Transport
module Rails
class Railtie < ::Rails::Railtie
initializer 'transport.configure' do |app|
...
end
end
end
end
I'm running into quite a few errors around how to require files property. Hoping for some insight.
There are files as so:
app/models
model.rb
app/workers
parent_worker.rb
app/workers/directory_1
directory_worker.rb
foo_worker.rb
bar_worker.rb
class DirectoryWorker < ParentWorker
end
class FooWorker < DirectoryWorker
def method_called_by_model
end
end
When I call the method, method_called_by_model I get the following error:
NameError: uninitialized constant Model::FooWorker
I've added the following to application.rb, didn't add app/workers since it should be loaded automatically according to the documentation.
config.autoload_paths << "#{Rails.root}/app/workers/directory_1"
When I require_relative the worker files in the model I get the following error referring to the inherited class being unknown:
NameError: uninitialized constant DirectoryWorker
from project/app/workers/directory_1/FooWorker.rb:2:in `<top (required)>'
Any have any ideas what I can do?
You need to namespace those workers since they are inside a directory.
First remove the autoload call you added.
Here's how the files should be named and what they should look like inside.
# app/workers/parent_worker.rb
class ParentWorker
end
# app/workers/directory_1/directory_worker.rb
class Directory1::DirectoryWorker < ParentWorker
end
# app/workers/directory_1/foo_worker.rb
class Directory1::FooWorker < Directory1::DirectoryWorker
def method_called_by_model
end
end
# app/workers/directory_1/bar_worker.rb
class Directory1::BarWorker < Directory1::DirectoryWorker
end
I have the following code in lib/test/company.rb:
module Test
class Company
# irrelevant stuff
end
end
In spec/model/request.rb, I've tried all of the following:
require "company"
require "lib/test/company"
require "lib/test/company.rb"
require Rails.root + "/lib/test/company.rb"
None of those works, at the class certainly isn't getting autoloaded. What's going on?
In your spec file:
require "test/company"
This is unnecessary if you'd like to autoload all modules/classes from lib. To do so, add to the config block in your application.rb file:
module YourApp
class Application < Rails::Application
config.autoload_paths += %W( #{config.root}/lib )
end
end
Addition:
You can then call Test::Company from the top-level namespace to access this class.
Try require "#{Rails.root}/lib/test/company.
I'd like to include TestModule in MyModule:
# in test_module.rb
module TestModule
SOMETHING = [1, 2, 3]
end
# in my_module.rb
module MyModule
include TestModule
def my_method
"testing"
end
end
I'm receiving this error:
Routing Error: uninitialized constant MyModule::TestModule
I've double-checked the rails naming convention. Any idea why this isn't working?
More info: config.autoload_paths += ... in application.rb is commented out. However other modules in /lib are being loaded somehow.
More info 2: I think rails can't see the new file test_module.rb. If I add a new module to an existing file containing a module then including the new module works. Is there some sort of rails clean-up or refresh process for the $LOAD_PATH or something?
You can also try with this:
# in my_module.rb
load 'test_module.rb'
module MyModule
include ::TestModule
def my_method
"testing"
end
end
to refer to top-level namespace.
Try adding a "require" to the top of the file like this:
# in my_module.rb
require 'test_module'
module MyModule
include TestModule
...