我目前有一个超类,它有一个函数,我希望所有子类在每个函数内调用.该函数应该像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) 我想在某些课程中发生某些事情时收到通知.我想以这样的方式设置它,使得我在这些类中的方法的实现不会改变.
我以为我会有以下模块:
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方法.)
我注意到我可能想要使用"模块+超级技巧".我不确定这是什么 - 也许有人可以启发我?
我有一个方法只采用一个参数:
def my_method(number)
end
Run Code Online (Sandbox Code Playgroud)
如果使用number < 2?调用方法,如何引发错误?通常,我如何定义方法参数的条件?
例如,我想在调用时出错:
my_method(1)
Run Code Online (Sandbox Code Playgroud) 是否可以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)