i am creating a rails application and there is a part that is causing me some trouble on the way i designed my code. I am feeling that i’m doing this a bit too messy and i would like to know if there is a design pattern or generally a better way to do this. The situation is like this :
I have a City model and the city can store wood, stone and gold. Those resources are changing over time based on their timestamps. They have their own attributes like amount, changed_timestamp.
Now, i thought that creating 3 separate models like wood_production, stone_production and gold_production seemed like a good idea, seemed pretty adequate. I also created delegators and virtual attributes so that i can execute something like :
city.wood or city.stone
However, the problems arise when i want to change the amount or timestamp for a specific resource type. Say that a building costs
{:wood => 200, :stone => 100, :gold => 50}
to be created. So say that the building is created and i now have to reduce the resources from the city. This would need me to do something like :
self.wood_production.update_attribute(:change_timestamp, Time.now)
self.wood -= v
self.save
The problem with this is that it’s resource specific. I would much more like to have a set_resource method that carries on with the procedure without caring about the resource type (without using ifs and more spaghetti).
How would you do it ?
The simplest way without changing anything and using the existing code you have is to just add a method like:
Calling
city.modify_resource!(:wood, -10)would subtract 10 wood and update the timestamp.It would also depend on how you’re storing the data though. Is the resource total stored with the city, or is it stored in *_production tables and
self.woodis just an alias towood_production?There aren’t many other ways of organizing your classes unless you want to go with a simpler method that stores more data per city, such as storing the
change_timestampwith the city model rather than in a separate table.