相关疑难解决方法(0)

如何拦截ruby中的方法调用?

我目前有一个超类,它有一个函数,我希望所有子类在每个函数内调用.该函数应该像rails中的before_filter函数一样,但我不确定如何实现before_filter.这是一个例子

class Superclass
  def before_each_method
    puts "Before Method" #this is supposed to be invoked by each extending class' method
  end
end

class Subclass < Superclass
  def my_method
    #when this method is called, before_each_method method is supposed to get invoked
  end
end
Run Code Online (Sandbox Code Playgroud)

ruby

10
推荐指数
2
解决办法
6375
查看次数

如何通过包含模块来包装Ruby方法的调用?

我想在某些课程中发生某些事情时收到通知.我想以这样的方式设置它,使得我在这些类中的方法的实现不会改变.

我以为我会有以下模块:

module Notifications
  extend ActiveSupport::Concern

  module ClassMethods
    def notify_when(method)
      puts "the #{method} method was called!"
      # additional suitable notification code
      # now, run the method indicated by the `method` argument
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

然后我可以将它混合到我的类中,如下所示:

class Foo
  include Notifications

  # notify that we're running :bar, then run bar
  notify_when :bar

  def bar(...)  # bar may have any arbitrary signature
    # ...
  end
end
Run Code Online (Sandbox Code Playgroud)

我的主要愿望是我不想修改:bar以使通知正常工作.可以这样做吗?如果是这样,我将如何编写notify_when实现?

此外,我正在使用Rails 3,所以如果有ActiveSupport或我可以使用的其他技术,请随时分享.(我查看了ActiveSupport :: Notifications,但这需要我修改bar方法.)


我注意到我可能想要使用"模块+超级技巧".我不确定这是什么 - 也许有人可以启发我?

ruby methods module

7
推荐指数
2
解决办法
6200
查看次数

定义方法参数的条件

我有一个方法只采用一个参数:

def my_method(number)

end
Run Code Online (Sandbox Code Playgroud)

如果使用number < 2?调用方法,如何引发错误?通常,我如何定义方法参数的条件?

例如,我想在调用时出错:

my_method(1)
Run Code Online (Sandbox Code Playgroud)

ruby methods

5
推荐指数
1
解决办法
122
查看次数

是否可以在Ruby中执行before_action(如在Rails中)?

是否可以before_action在某些指定的方法之前调用一个,比如在rails中?

class Calculator
  before_action { raise Exception, "calculator is empty" if @numbers.nil? }, 
                 only: [:plus, :minus, :divide, :times]

  def push number
    @numbers ||= [] 
    @numbers << number
  end

  def plus
    # ... 
  end

  def minus
    # ... 
  end

  def divide
    # ... 
  end

  def times
    # ... 
  end

    # ... 
end
Run Code Online (Sandbox Code Playgroud)

ruby

4
推荐指数
2
解决办法
3979
查看次数

标签 统计

ruby ×4

methods ×2

module ×1