【问题标题】:Running code before every method in a class (Ruby)在类中的每个方法之前运行代码(Ruby)
【发布时间】:2011-10-22 21:44:14
【问题描述】:

我想跟踪在我构建的类的实例上运行的所有方法。

目前我这样做:

class MyClass
    def initialize
        @completed = []
    end

    # Sends a welcome and information pack to the person who requested it
    def one_of_many_methods
    unless @completed.include? __method__
            # Do methody things
            @completed.push __method__
        end
    end
    alias :another_name :one_of_many_methods
    # Calling myClassInstance.another_name will insert
    # :one_of_many_methods into @completed.
    # Methody things should not now be done if .another_name
    # or .one_of_many_methods is called.
end

但是当我的课堂上有很多方法时,这会变得非常费力。我在重复自己!有没有办法跟踪被调用的方法并只允许它们被调用一次,就像我在上面所做的那样,但不必在每个方法中重复该块?

谢谢!

(PS。我使用的是 Ruby 1.9)

【问题讨论】:

    标签: ruby class methods


    【解决方案1】:

    这听起来像是Proxy 对象的完美用例。幸运的是,Ruby 的动态特性使其非常容易实现:

    class ExecuteOnceProxy
    
      def initialize(obj)
        @obj = obj
        @completed = []
      end
    
      def method_missing(method, *args)
        unless @completed.include?(method)
          args.empty? ? @obj.send(method) : @obj.send(method, args)
          @completed << method
        end
      end
    end
    

    只需在构造函数中传递原始对象即可初始化您的代理:

    proxy = ExecuteOnceProxy.new(my_obj)
    

    【讨论】:

    • +1。 JP,我建议查看 Design Patterns in Ruby,它涵盖了 Ruby 中的许多常见设计模式,包括代理。
    【解决方案2】:

    method_missing


    有些框架可以做这样的事情,但要回答你的问题,是的,有一个简单的方法。

    只编写一次代码的简单方法是将整个类放在前端并实现method_missing. 然后您可以一次发现一个真正的方法,因为在初始调用时发现每个方法都“缺失” .

    【讨论】:

    • 我了解这种技术,但我不明白您所说的前端是什么意思。你能举个例子吗?
    【解决方案3】:

    我认为您的问题有新的解决方案。

    前段时间,Tobias Pfeiffer 发布了after_dogem

    【讨论】:

      【解决方案4】:

      这不是答案,因为我没有足够的声誉来发表评论,但请注意@emboss 发布的答案有错误(缺少星号)。

      args.empty? ? @obj.send(method) : @obj.send(method, args)

      应该是

      args.empty? ? @obj.send(method) : @obj.send(method, *args)

      否则该方法将接收一个参数:您尝试传递的参数数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-02
        • 1970-01-01
        • 2017-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多