【发布时间】:2010-12-30 23:59:45
【问题描述】:
我的班级很大,有很多方法,而且开始变得有点杂乱无章,难以导航。我想把它分解成模块,每个模块都是类和实例方法的集合。也许是这样的:
更新:我现在意识到这是一个非常糟糕的例子。您可能不想将验证或属性移出核心类。
class Large
include Validations
include Attributes
include BusinessLogic
include Callbacks
end
在阅读了 Yehuda 关于Better Ruby Idioms 的帖子后,我很好奇其他人是如何解决这个问题的。这是我能想到的两种方法。
第一种方法
module Foo
module Validations
module ClassMethods
def bar
"bar"
end
end
module InstanceMethods
def baz
"baz"
end
end
end
class Large
extend Validations::ClassMethods
include Validations::InstanceMethods
end
end
第二种方法
module Foo
module Validations
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def bar
"bar"
end
end
def baz
"baz"
end
end
class Base
include Validations
end
end
我的问题是:
- 有没有更好的方法来做到这一点?
- 如何以最少的魔法为一组类/实例方法获得单线模块 mixin?
- 如何在不给类本身命名空间的情况下将这些模块命名为基类?
- 您如何组织这些文件?
【问题讨论】:
-
我在engineyard 的博客文章中找到了我一直在寻找的答案:engineyard.com/blog/2010/let-them-code-cake
标签: ruby refactoring module