Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require some lib files from anywhere

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

like image 820
Zoz Avatar asked Jul 30 '13 15:07

Zoz


People also ask

How do I require a Ruby file?

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.

How require works Ruby?

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.

What goes in lib folder Rails?

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.

What is lib folder?

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.


2 Answers

You can autoinclude everything under the lib folderand 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/**/"] 
like image 178
Vecchia Spugna Avatar answered Sep 25 '22 10:09

Vecchia Spugna


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.

like image 45
Sachin Singh Avatar answered Sep 22 '22 10:09

Sachin Singh