How to enable custom .rb script in a Rails application

Ok, I have a Ruby script that should be included in many Rails applications. Therefore, I do not want to break it into pieces and paste it into a specific application, but it is better to save it in 1 piece, and the Rails application will load it. A script is required mainly from models, mailers, and rarely controllers.

So, if my script is equal to tools.rb , where in my Rails file tree should I put it and how / where in my Rails application do I enable it? In addition, the script comes with a YAML file.

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

+4
source share
3 answers

You can save all the extra stuff in /app/modules or /lib . And I prefer lib . Having placed in the lib folder, require it in any initializer (or create)

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

And tadaa !! You can use this corresponding class / module anywhere in your rails application!

And all YAML files should be placed in /config/ .

*** Fix syntax in '/ lib / tools'

+6
source

You can include your own .rb files in the lib folder . You can include modules, classes ... etc. Under your own rb files.

If you want to autostart or auto-update your custom library code, you must open your config/application.rb and add the following line, for example:

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

You can take a look at:

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

The yaml files must be inside the /config/ folder.

Hello!

+5
source

If you have a module or class defined in the script and use that module or class in the application, you just put it in lib . It will be available anywhere in the application. Download the file if you need to initialize something that your application needs. If this is not necessary, do not load things. If you think that it should be downloaded before launching the application. Then you can enter config/initializers

yml files can be loaded as shown below in some initializers file (maybe in your tools.rb ):

  MY_TOOLS = YAML.load_file("#{RAILS_ROOT}/config/tools.yml") 

Then you can use MY_TOOLS anywhere in the application.

+2
source

All Articles