Tag: mixins

为什么模块的单例方法在混合的下游特征类中不可见?

我理解常规方法查找路径,即class, superclass/module, all the way up to BasicObject 。 我认为链的单例版本也是如此,但是当您在元链中混合模块时似乎并非如此。 我很感激,如果有人能解释为什么在下面的示例中,当我将此模块包含在Vehicle的本征类中时,调用Automobile模块的banner方法而不是其单例版本。 module Automobile def banner “I am a regular method of Automobile” end class << self def banner "I am a singleton method of Automobile" end end end class Vehicle def banner "I am an instance method of Vehicle" end class << self include Automobile […]

Ruby:模块,Mixins和Block令人困惑?

以下是我试图从Ruby Programming Book中运行的代码http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html 为什么product方法没有给出正确的输出? 我用irb test.rb运行它。 我正在运行Ruby 1.9.3p194 。 module Inject def inject(n) each do |value| n = yield(n, value) end n end def sum(initial = 0) inject(initial) { |n, value| n + value } end def product(initial = 1) inject(initial) { |n, value| n * value } end end class Array include Inject end […]

Ruby中’include’和’prepend’有什么区别?

来自模块 模块#append_features(mod)→mod =>当这个模块包含在另一个模块中时,Ruby在这个模块中调用append_features,并在mod中传递接收模块。 Ruby的默认实现是将此模块的常量,方法和模块变量添加到mod,如果此模块尚未添加到mod或其祖先之一。 模块#prepend_features(mod)→mod =>当这个模块被放在另一个模块中时,Ruby在这个模块中调用prepend_features,并在mod中传递接收模块。 Ruby的默认实现是将此模块的常量,方法和模块变量覆盖到mod,如果此模块尚未添加到mod或其祖先之一。 任何人都可以帮助我理解以下问题: Module哪些更多function被定义为append和prepend除了那些默认值? 他们的function如何不同? 何时使用append_features和prepend_features ? 上面两条粗线之间有什么区别?

Objective-C是否像Ruby一样支持Mixin?

在Ruby中,有模块,您可以通过“混入”模块来扩展类。 module MyModule def printone print “one” end end class MyClass include MyModule end theOne = MyClass.new theOne.printone >> one 在Objective-C中,我发现我有一组常用的方法,我想要一些Class来“inheritance”。 如果不创建一个公共类并从该公共类派生所有其他方法,我可以通过什么方式实现这一目标?

在多个模型中放置常见代码的位置?

我有两个包含相同方法的模型: def foo # do something end 我应该把它放在哪里? 我知道常用代码在Rails应用程序的lib目录中。 但是如果我把它放在lib中一个名为’ Foo ‘的新类中,并且我需要将它的function添加到我的两个ActiveRecord models ,我是这样做的: class A < ActiveRecord::Base includes Foo class B < ActiveRecord::Base includes Foo 然后A和B都将包含foo方法,就像我在每个方法中定义它一样?

获取包含模块的类列表

我有一个mixin,我想获得包含它的所有类的列表。 在mixin模块中,我做了以下事情: module MyModule def self.included(base) @classes ||= [] @classes << base.name end def self.classes @classes end end class MyClass include MyModule end 这非常有效: > MyModule.classes #=> nil > MyClass.new #=> # > MyModule.classes #=> [“MyClass”] 现在,我想将这部分提取到一个单独的模块中,该模块可以包含在我的其他mixins中。 所以,我想出了以下内容: module ListIncludedClasses def self.included(base) p “…adding #{base.name} to #{self.name}.classes” @classes ||= [] @classes << base.name base.extend(ClassMethods) end […]