Ruby on rails 从包含模块的类中的重写方法调用模块中定义的方法
如果模块中定义的方法在类中被重写,是否可以调用该方法Ruby on rails 从包含模块的类中的重写方法调用模块中定义的方法,ruby-on-rails,ruby,Ruby On Rails,Ruby,如果模块中定义的方法在类中被重写,是否可以调用该方法 Class A include bmodule def greeting super if some_condition_is_true end end module bmodule included do has_many :greeters def greeting puts 'hi' end end end A.new.greeting如果某个条件为真,则需要点击b模块的问候语 我
Class A
include bmodule
def greeting
super if some_condition_is_true
end
end
module bmodule
included do
has_many :greeters
def greeting
puts 'hi'
end
end
end
A.new.greeting
如果某个条件为真,则需要点击b模块的问候语
我试着预编并加入模块,但没有成功。可以这样做吗?您必须先保存原始方法,然后再覆盖它:
Class A
include bmodule
alias_method :original_greeting, :greeting
def greeting
original_greeting if some_condition_is_true
end
end
这就是doc的例子
Rails关注点中包含的do
块可以在基础上调用类方法。因此,我认为在这种情况下不需要使用它。您可以使用该方法,它提供了很大的灵活性
module M1
def meth(arg)
yield arg
end
end
module M2
def meth(arg)
yield arg
end
end
如果出于某种原因,您想使用prepend
而不是include
,C.antesors
如下所示:
class C
prepend M1
prepend M2
end
C.ancestors
#=> [M2, M1, C, Object, Kernel, BasicObject]
因此,您只需相应地修改
测试。是的,您可以做到这一点,而且几乎完全正确。只需1)大写b模块
,这样ruby就不会对您大喊大叫;2)在定义A时使用小写类
;3)include ActiveSupport::如果您使用的是included
,请关注;4)将问候语方法移出included块。包含的块用于在类级别运行东西,实例方法定义不应在其中
module Bmodule
extend ActiveSupport::Concern
included do
has_many :greeters
end
def greeting
puts 'hi'
end
end
class A
include Bmodule
def greeting
super if some_condition_is_true
end
end
A.new.greeting
请提供一个最小的可重复示例()。现在,您的代码包含许多问题,这些问题使它成为无效的Ruby。但总的来说,您正在朝着正确的方向前进:super
完成了这项工作……这是一个替代方案,但不是必需的。
C.ancestors
#=> [C, M2, M1, Object, Kernel, BasicObject]
c = C.new
c.test(:C) { |m| "meth is from #{m}" }
#=> "meth is from C"
c.test(:M2) { |m| "meth is from #{m}" }
#=> "meth is from M2"
c.test(:M1) { |m| "meth is from #{m}" }
#=> "meth is from M1"
class C
prepend M1
prepend M2
end
C.ancestors
#=> [M2, M1, C, Object, Kernel, BasicObject]
module Bmodule
extend ActiveSupport::Concern
included do
has_many :greeters
end
def greeting
puts 'hi'
end
end
class A
include Bmodule
def greeting
super if some_condition_is_true
end
end
A.new.greeting