红宝石图案问题
抱歉这个蹩脚的标题:我不知道如何总结这个......
我有一组类是公式(或公式,如果你喜欢),以及其他类集(称为外部类),它们将利用它们。
公式类有许多属性(比如大约 20 个)和一个计算函数。外部类是持久性类,因此具有公式类的所有属性以及它自己的更多属性。
在我的系统中,用户可以配置要使用的公式类,并且实际上可以选择使用多个公式进行计算,例如用于比较报告。
我正在尝试弄清楚如何在内部/公式类和外部/持久性类之间传输属性值,而无需一行又一行的 inner.x = external.x
代码。
在我看来,我不能使用:
class Outer
include Formula1
end
...因为我希望实际的 Formula 类是可配置的。
我想到的一个想法是,我可以有一组属性从外部类传递下来,然后循环它们并发送
,如下所示:
# not tested
['x', 'y', 'z'].each{|a|@formula.send("#{a.to_sym}=", self.send("#{a.to_sym}") }
我应该考虑的任何其他红宝石魔法或模式?
谢谢,
Sorry for the lame title: I'm not sure how to sum this one up...
I have a set of classes that are formulas (or formulae if you like), and other set of classes (call them outer classes) that will utilize them.
The formula classes have many attributes (say about 20) and a calculate function. The outer class is a the persistence class and therefore has all the attributes of the formulae class and several more of its own.
In my system, users can configure which formulae class to use, and indeed may chose to calculate using more than one formula for a comparison report for example.
I'm trying to work out how I can transfer attribute values between the inner/formula class and the outer/persistence class without line after line of inner.x = outer.x
code.
It seems to me that I can't use:
class Outer
include Formula1
end
...because I want the actual Formula class to be configurable.
One idea that springs to mind is I could have an array of attributes to pass down from my outer class, and loop over them and send
, something like this:
# not tested
['x', 'y', 'z'].each{|a|@formula.send("#{a.to_sym}=", self.send("#{a.to_sym}") }
Any other ruby magic or patterns I should be considering?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您正在寻找一个策略模式来插入公式,如果您不想通过公式实例调用公式的属性,则可能需要一个外观。
制定策略的简单方法是将 Formula 的实例作为 Outer 的属性之一:
为了处理大量访问器,也许您可以尝试缺少方法来调用,或者在调用方法时为您定义和调用方法?
Sounds like you're look for a Strategy pattern to plug in the formula and then maybe a Facade if you don't want to call the formula's attribute via the formula instance.
Easy way to make a Strategy is to make an instance of Formula one of Outer's attributes:
to deal with lots of accessors perhaps you could try method missing to either call, or define and call the methods for you as they're called?
我的 ruby-fu 很低,我可能错过了您要求的一些微妙之处,所以这可能不是最好的选择,但是您可以有一个模块,您可以在其上定义属性,然后将该模块包含在您的 Outer 和 Formula 类中,像这样:
My ruby-fu is low and I am probably missing some subtlety of your requirement, so this is probably not the best option, but you could have a module on which you define the attributes and then include that module in your Outer and Formula classes, like this: