Hi,
Newbie here. I would like to know where do I keep modules that I can include in the Models as well as Controllers in the app? Where do I store the modules, which files?
Hi,
Newbie here. I would like to know where do I keep modules that I can include in the Models as well as Controllers in the app? Where do I store the modules, which files?
You can put them in the lib folder
Ok If I put them in the lib folder I can include them in both models and controllers right? Any special syntax I should be aware of? And I just create a new .rb file in the lib folder and drop the module(s) in right? Sorry just confirming and Thanks!
No special syntax. Just ‘require’ to load the module to make the application aware of that code’s existence. Then include to add the methods of that module to either the model or controller.
module CoolCode def do_stuff Rails.logger.debug “do stuff” end end
require ‘cool_code’
class WelcomeController < ApplicationController include CoolCode def index do_stuff end end
require ‘cool_code’
class Post < ActiveRecord::Base include CoolCode
def some_method do_stuff end
end
Also, if you put
config.autoload_paths += %W(#{config.root}/lib)
in config/application.rb, then you don’t need to use require ‘cool_code’.
Hey Dermot, Thanks a Ton that did if for me