使一个模块从 Ruby 中的另一个模块继承
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10158730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making a module inherit from another module in Ruby
提问by beakr
I'm making a small program for Rails that includes some of my methods I've built inside of a module inside of the ApplicationHelpermodule. Here's an example:
我正在为 Rails 制作一个小程序,其中包括我在模块内部ApplicationHelper模块中构建的一些方法。下面是一个例子:
module Helper
def time
Time.now.year
end
end
module ApplicationHelper
# Inherit from Helper here...
end
I know that ApplicationHelper < Helperand include Helperwould work in the context of a class, but what would you use for module-to-module inherits? Thanks.
我知道这一点ApplicationHelper < Helper并且include Helper可以在类的上下文中工作,但是您将使用什么来进行模块到模块的继承?谢谢。
回答by DigitalRoss
In fact you candefine a module inside of another module, and then includeit within the outer one.
实际上,您可以在另一个模块内部定义一个模块,然后将其包含在外部模块中。
so ross$ cat >> mods.rb
module ApplicationHelper
module Helper
def time
Time.now.year
end
end
include Helper
end
class Test
include ApplicationHelper
def run
p time
end
self
end.new.run
so ross$ ruby mods.rb
2012
回答by Dane Lowe
One potential gotcha is that if the included module attaches class methods, then those methods may be attached to the wrong object.
一个潜在的问题是,如果包含的模块附加了类方法,那么这些方法可能会附加到错误的对象上。
In some cases, it may be safer to include the 'parent' module directly on the base class, then include another module with the new methods. e.g.
在某些情况下,将“父”模块直接包含在基类中可能更安全,然后使用新方法包含另一个模块。例如
module ApplicationHelper
def self.included(base)
base.class_eval do
include Helper
include InstanceMethods
end
end
module InstanceMethods
def new_method
#..
end
end
end
The new methods are not defined directly in ApplicationHelperas the include Helperwould be run after the method definitions, causing them to be overwritten by Helper. One could alternatively define the methods inside the class_evalblock
新方法没有直接定义,ApplicationHelper因为include Helper将在方法定义之后运行,导致它们被Helper. 也可以在class_eval块内定义方法

