开发者

avoid the same code at the beginning of a set of methods

开发者 https://www.devze.com 2023-03-07 01:37 出处:网络
Issue: I am using a global constant STORE_DATA_ENABLED to enable a module I wrote (StoreData): Example:

Issue: I am using a global constant STORE_DATA_ENABLED to enable a module I wrote (StoreData): Example:

STORE_DATA_ENABLED = false

...

module StoreData

    def a
        return unless STORE_DATA_ENABLED
        ...
    end

    def b
        return unless STORE_DATA_ENABLED
        ...
    en开发者_JAVA技巧d

    def c
        return unless STORE_DATA_ENABLED
        ...
    end

    ...

end

I think there is a way to disable the module without checking all the methods in the module. Any Ideas to DRY this code ?


Use a before_filter. This is called before every method call in your module:

module StoreData

  before_filter :store_data_enabled

  def a
    ...
  end

  private
    def store_data_enabled
      STORE_DATA_ENABLED # return implicit true/false
    end
end

EDIT: a ruby-only approach. This uses the module initializer to re-create all public methods in the module and make them return nil. I did not try how this behaves when you have arguments in your methods.

module M  

  # this is called while module init
  def self.included(base)
    unless STORE_DATA_ENABLED
      # iterate over public methods of this instance
      public_instance_methods.each do |m|
        # overwrite all methods, does not care about arguments
        define_method(m) { return nil }
      end
    end
  end

  def a
    ...
  end 

end
0

精彩评论

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