开发者

Trying to understand how a Controller uses a Plugin/Module

Ok so I am using some module/lib/plugin (not sure of the exact name), let's say its a authentication/authorization plugin like: http://github.com/technoweenie/restful-authentication

class HomeController < ApplicationController


    some_module_name_here


end

Now just from adding the code above 'some_module_name_here', I can access to methods from that module.

What is that line of code doing that gives me access to methods/objects from the module?

Is that declaring a variable 开发者_Python百科like in say java/c#:

public SomeModule _someModule; 

I know that plugins/modules basically extend the class under the covers, but how does it do this with a single line of code?

Is it called in the constructor somehow?


When you create a ruby plugin, and load it into the rails app via environment.rb, bundler, or a require call, the methods are loaded as "modules" that can be called. The ones that act like you're talking about will have an extra method called acts_as_list or something similar. All that method does is include the methods of the module into the class where that line was called.

Here's an example, which you could include in your app's lib folder and play with:

module Bellmyer
  module Pointless
    def self.included(base)
      base.extend PointlessMethods
    end

    module PointlessMethods
      def acts_as_pointless
        unless included_modules.include? InstanceMethods
          extend ClassMethods
          include InstanceMethods
        end
      end
    end

    module ClassMethods
      def pointless_class?
        true
      end
    end

    module InstanceMethods
      def pointless_instance?
        true
      end
    end
  end
end

The module is available to any ruby class in your app, but the methods don't actually get loaded until you call acts_as_pointless, which then includes and extends your class with the methods listed. Only the acts_as_pointless method is immediately available to the model. This is the standard pattern for an ActiveRecord plugin.


That's not how it works.

When the plugin or gem is loaded it adds a class method to, in this case, ApplicationController named some_module_name. When you call that methods, a bunch of other class and instance methods are included.

Check out your favourite gem or plugin to see how they do it exactly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜