ruby oo 设计问题我应该重新打开课程还是使用扩展模式

发布于 2024-10-17 02:59:45 字数 567 浏览 1 评论 0原文

所以我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

末が日狂欢 2024-10-24 02:59:45

您应该将方法放在模块中并将该模块包含在类中。这种方式更可取,因为更容易看到方法来自哪里(例如,在回溯中),并且如果发现这些方法也可以在其他类中使用,则更容易重用这些方法。

例如:

module Conversions
  def to_pdf
  end
  def to_csv
  end
end

class RubyModel
  include Conversions
end

to_pdfto_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:

module Conversions
  def to_pdf
  end
  def to_csv
  end
end

class RubyModel
  include Conversions
end

It might also be a good idea to put to_pdf and to_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.

后知后觉 2024-10-24 02:59:45

如果语言功能运行良好,则保持简单并使用它。

设计模式是针对语言表达能力不足的情况记录的解决方法。 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文