1

我有一个 gem,其中包含一个设计为在 Rails 中作为 before_filter 运行的方法:

before_filter :method_in_gem

当他们想在他们的应用程序中调用这个 before_filter 时,由开发人员决定(即我不想以任何方式对他们强制执行它)

如何以控制器能够获取的方式公开此方法?我有我的方法gem_name/lib/controllers.rb

如果相关,我的 gem 是用 bundler 创建的。

4

1 回答 1

1

尝试以下

module ModuleName
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def meth(args)
      before_filter :bf_method

      include ModuleName::InstanceMethods
    end 
  end 

  module InstanceMethods
    def bf_method
      # ...
    end 
  end 
end

然后只需将模块包含在您的控制器中

class ApplicationController < ActionController::Base
  include ModuleName
end
于 2013-02-27T14:09:25.187 回答