I'll explain my situation.
Here is my file tree in my rails application :
lib/my_module.rb
require 'my_module/my_file' module My_module end
lib/my_module/my_file.rb
class Tweetag::Collector (...) end
I've made a ruby script that I've put in config/jobs/
I really don't understand how I am supposed to require the file my_file.rb in this file.
require '../../my_module/my_file.rb'
It gives me `require': cannot load such file
Same error with just require 'my_module' which is what I do in my controllers...
Someone here to explain to me ? Thanks a lot
the require_relative method It first finds the requiring file or library path, and then determine an absolute path according to the required file or library. When the file or library is loaded then the absolute path is added to the $LOADED_FEATURES . This script runs in the same directory as our hello. rb file.
In Ruby, the require method is used to load another file and execute all its statements. This serves to import all class and method definitions in the file.
In Rails's directory structure as far back as I can recall, there's always been a lib folder. This folder is for files that don't belong in the app folder (not controllers, helpers, mailers, models, observers or views), such as modules that are included into other areas of the application.
lib – Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path.
You can autoinclude everything under the lib folder
and avoid these problems:
Type this your file in config/application.rb
config.autoload_paths += %W(#{config.root}/lib) config.autoload_paths += Dir["#{config.root}/lib/**/"]
If you want to require only a specific file then, do something relative to Rails root like this
for example: -- lib/plan.rb module Plan ...some code... end
and if you want to require it only in some model, say app/models/user.rb
do in user model
require "#{Rails.root}/lib/plan" class User < ActiveRecord::Base include Plan end
if you want it to be available everywhere
one solution is given by @VecchiaSpugna
or you can create a ruby file in config/initializers folder
and require all file over there one by one
OR
try this require '../../my_module/my_file' instead of require '../../my_module/my_file.rb'
You don't need to specify extension for a file in require.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With