在rubygem中提供before_filter

时间:2013-02-27 14:01:44

标签: ruby-on-rails ruby rubygems

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

before_filter :method_in_gem

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

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

中有我的方法

如果它是相关的,我的宝石是用bundler创建的。

1 个答案:

答案 0 :(得分: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