Reputation: 4835
I am currently trying to put together a model structure for performing various calculations, the formulas for which will be stored within the models.
Currently, I have an operand model, which is connected via many-to-many with the operations model. This works fine as long as I can always do a simple calculation (i.e. without intermediate steps).
Where I have a problem is if I need to (for example) subtract the result of one operation from the result of another. I'm aware that I could use a second model to perform calculations on operations, but I will run into the same problem further up the chain (i.e. if I need to perform an operation on the result of the calculation).
As such, what I need is essentially a way to nest the operations - i.e. an operation could take as its operands a normal operand from the operand model, or the result of another operation. Is there a way for the operations model to essentially self reference like this?
Thanks!
Upvotes: 1
Views: 108
Reputation: 13414
This is really more of an object modeling question than a rails question -- and without understanding the domain models in more detail I'm not sure I can help a great deal.
But as I think about calculators and how I've seen simple sets of operations/operand programming work, there have been a couple patterns I've seen that may be helpful:
Do you have a 'current result' model that stores the results after each operation is performed? I'd think that each operation could be performed on a 'current result' model and it could store whatever the current result is.
I've also seen situations where the idea of a 'register' was used as temporary storage for intermediate results. 'store to register 1', for example, would be an operation by itself. If you developed at 'register' object that you could store results into and fetch them from (or even that you could perform an operation on and leave the result in the register) that may be helpful.
Does this make sense in your domain?
Upvotes: 1
Reputation: 2276
I don't know if I understand your question very well, but it seemed to me that you want to perform operations on an attribute before saving it. You can use super()
to do that.
def attribute=(val)
new_val = #any types of operations on val
super(val)
end
Upvotes: 0