ruby oo 设计问题我应该重新打开课程还是使用扩展模式
所以我有一个 ruby 对象,我需要将其创建为 pdf 和 excel 行和 cvs 行,
到目前为止我已经创建了一个新类,其中包含一种方法来接收该对象并执行必要的操作来生成 pdf 、 excel 、 csv
我一直在阅读《敏捷软件开发、原则、模式和实践》,它提到了扩展方法,所以我打算这么做,但由于这是 ruby,我应该在另一个文件中重新打开该类,并将方法添加到其中将它们与主类分开
,因此
文件 ruby_model.rb
class RubyModel < ActiveRecord::Base
end
然后执行
ruby_model_pdf.rb
class RubyModel
def to_pdf
end
end
ruby_model_cvs.rb
class RubyModel
def to_csv
end
end
或者我应该使用对象扩展模式?
干杯
so I have an ruby object that i need to create as a pdf and excel row and cvs row
so far I've created a new class with a method to take in the object and do the necessary stuff to produce the pdf , excel , csv
I've been reading Agile Software Development, Principles, Patterns, and Practices and it mentioned the extension method so i was going to do but since this is ruby should i just be reopening the class in the another file and added the methods on there to separate them from the main class
so
file ruby_model.rb
class RubyModel < ActiveRecord::Base
end
then do
ruby_model_pdf.rb
class RubyModel
def to_pdf
end
end
ruby_model_cvs.rb
class RubyModel
def to_csv
end
end
or should i go with with the object extension pattern?
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将方法放在模块中并将该模块包含在类中。这种方式更可取,因为更容易看到方法来自哪里(例如,在回溯中),并且如果发现这些方法也可以在其他类中使用,则更容易重用这些方法。
例如:
将
to_pdf
和to_csv
放在不同的模块中也可能是个好主意,除非您想混合使用一个模块,但总是想混合使用在另一个。这一切都假设这些方法不属于类本身,但从名称来看它们不属于类本身。
You should put your methods in a module and include the module in the class. This way is preferable because it's easier to see where the methods came from (in a backtrace, for example), and it's easier to reuse the methods if it turns out that they can be used in other classes too.
For example:
It might also be a good idea to put
to_pdf
andto_csv
in different modules, unless it's the case that if you want to mix in one you always want to mix in the other.This all assumes that the methods don't belong in the class itself, but judging from the names they don't.
如果语言功能运行良好,则保持简单并使用它。
设计模式是针对语言表达能力不足的情况记录的解决方法。 Ruby 的一个例子是 Iterator,它通过块和
Enumerable
。If the language feature works fine, then keep it simple and use it.
Design patterns are documented workarounds for cases where the language is not expressive enough. A Ruby example would be Iterator, which is made redundant by blocks and
Enumerable
.