Rails /lib modules and

后端 未结 5 536
死守一世寂寞
死守一世寂寞 2020-11-27 09:43

I am writing a custom wrapper for open_flash_chart plugin. It\'s placed in /lib and load it as a module in ApplicationController.

5条回答
  •  清歌不尽
    2020-11-27 10:03

    What worked for me, besides uncommenting config.autoload_paths (I’m on Rails 3.1.3), was to create a initializer like this:

    #config/initializers/myapp_init.rb
    require 'my_module'    
    include MyModule
    

    This way I can call mymodule methods from anywhere and as class methods Model.mymodule_method or as instance methods mymodel.mymodule_method

    Maybe some expert may explain the implications of this. By now, use it at your own risk.

    Edit: Afterwards, I think a better approuch would be:

    create a initializer like this:

    #config/initializers/myapp_init.rb
    require ‘my_module’
    

    Include the module where needed, like this:

    1) if you want to use it as "Class Methods" use "extend":

    class Myclass < ActiveRecord::Base
       extend MyModule
       def self.method1
          Myclass.my_module_method
       end
    end
    

    2) if you want to use it as "Instance Methods" include it inside Class definition:

    class Myclass < ActiveRecord::Base
    include MyModule
       def method1
          self.my_module_method 
       end
    end
    

    3) remember that include MyModule refers to a file my_module.rb in your load path that must be required first

提交回复
热议问题