Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include custom .rb script in Rails app

Ok, I've got this Ruby script that is supposed to be included in many Rails apps. So I don't want to break it down to pieces and jam it into a particular app, but would rather keep it in 1 piece and have Rails app load it instead. The script would be required mostly from models, mailers and rarely controllers.

So if my script is tools.rb, where in my Rails file tree should I put it and how/where in my Rails app should I include it? Also the script comes with YAML file.

Its my second day learning Rails, so please bear with me.

like image 656
if __name__ is None Avatar asked Feb 16 '13 15:02

if __name__ is None


2 Answers

You can keep all the extra stuff in either /app/modules or /lib. And i prefer lib. After putting in the lib folder, require it in any initializer (or create one)

require "./lib/tools" in /config/initializers/tools.rb

And tadaa !! You can use that corresponding class/module anywhere in the rails application !!

And all the YAML files should be put in /config/.

*** fix syntax in '/lib/tools'

like image 153
Ramandeep Singh Avatar answered Nov 02 '22 23:11

Ramandeep Singh


You can include your own .rb files on lib folder. You can include, modules, class...etc under your own rb files.

If you want autoload or autorequire your custom library code, you must open your config/application.rb and add the next line for example:

config.autoload_paths += %W(#{config.root}/extras #{config.root}/lib)

You can take a look to:

http://reefpoints.dockyard.com/ruby/2012/02/14/love-your-lib-directory.html

You yaml files should be inside /config/ folder.

Regards!

like image 25
hyperrjas Avatar answered Nov 03 '22 01:11

hyperrjas