Business logic dependent on model attribute

情到浓时终转凉″ 提交于 2019-12-25 08:58:28

问题


I have a User model that has an introduced_by attribute. Based on that attributes value, I calculate my commission differently. What would be the best, most flexible way of doing this?

Should I do a switch, or maybe put everything in a flat file? Also, should I create a Commission model?


回答1:


It's a very broad question, as there is no code and no example. However, it seems to be the perfect case of a Strategy design pattern.

What I would do, is to create a class that represents the strategy for every specific range of attribute values.

E.g

PersonalCommission
CompanyCommission
HighValueCommission
DefaultCommission

Each class has a single method, let's say calculate that you can call passing an instance of the object and that returns the value of the commission.

Wherever you need to perform the calculation, just initialize a new Commission strategy object based on the User attribute and call calculate on it.

You don't even have to use a switch, as you can initialize the class dynamically.

strategy = "#{user.introduced_by}Commission".constantize
strategy.new.compute(whatever)

Of course, that's just a very simple example you'll have to adapt to your needs.



来源:https://stackoverflow.com/questions/34090617/business-logic-dependent-on-model-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!