乔纳森,
我不确定您是否仍然对此感到疑惑,但是在 ruby 中使用模块有两种不同的方法。 A.)您在代码中直接使用自包含形式 Base::Tree.entity(params) 的模块,或 B.)您将模块用作 mixins 或辅助方法。
A.将允许您将模块用作命名空间模式。这对于可能发生方法名称冲突的大型项目很有用
module Base
module Tree
def self.entity(params={},&block)
# some great code goes here
end
end
end
现在您可以使用它在代码中创建某种树结构,而不必为每次调用 Base::Tree.entity 实例化一个新类。
进行命名空间的另一种方法是逐类进行。
module Session
module Live
class Actor
attr_accessor :type, :uuid, :name, :status
def initialize(params={},&block)
# check params, insert init values for vars..etc
# save your callback as a class variable, and use it sometime later
@block = block
end
def hit_rock_bottom
end
def has_hit_rock_bottom?
end
...
end
end
class Actor
attr_accessor :id,:scope,:callback
def initialize(params={},&block)
self.callback = block if block_given?
end
def respond
if self.callback.is_a? Proc
# do some real crazy things...
end
end
end
end
现在我们的课程有可能重叠。我们想知道,当我们创建一个 Actor 类时,它是正确的类,所以这就是命名空间派上用场的地方。
Session::Live::Actor.new(params) do |res|...
Session::Actor.new(params)
B.混音
这些是你的朋友。每当您认为必须在代码中多次执行某项操作时,请使用它们。
module Friendly
module Formatter
def to_hash(xmlstring)
#parsing methods
return hash
end
def remove_trailing_whitespace(string,&block)
# remove trailing white space from that idiot who pasted from textmate
end
end
end
现在,当您需要将 xmlstring 格式化为哈希,或删除任何未来代码中的尾随空格时,只需将其混入即可。
module Fun
class Ruby
include Friendly::Formatter
attr_accessor :string
def initialize(params={})
end
end
end
现在你可以在你的类中格式化字符串了。
fun_ruby = Fun::Ruby.new(params)
fun_ruby.string = "<xml><why><do>most</do><people></people><use>this</use><it>sucks</it></why></xml>"
fun_ruby_hash = fun_ruby.to_hash(fun_ruby.string)
希望这是一个足够好的解释。上面提出的观点是扩展类的好例子,但是对于模块,困难的部分是何时使用 self 关键字。它指的是 ruby 对象层次结构中对象的范围。因此,如果您想将模块用作混入,并且不想声明任何单例,请不要使用 self 关键字,但是如果您想在对象中保持状态,只需使用类并混合 -在你想要的模块中。