Module or Inheritance?
I have an Inventory and a Warehouse model. There is also a User and OwnedItem model. An OwnedItem is polymorphic to inventory and warehouse, so that a warehouse or inventory can have an owned item for a certain user.
Now, a warehouse and an inventory have certain similarities. For instance, they handle the slots i开发者_如何学Gon a pretty similar manner. To illustrate, this is an inventory function i created :
def empty_slots_count
self.max_slots - self.owned_items.inventory.count
end
This one returns the empty slots number of the inventory. This function would be almost the same for the warehouse(identical expect from the .inventory part). So, now i'm wondering if a module applies here.
Though a module may be ok, it does not feel too natural. If i were doing that in C++, i would definately use inheritance. I would probably have another class, maybe named something like SlotManager that would handle this, and my Inventory class would inherit that and use it.
But Ruby does not support multiple inheritance (only mixins? don't really know much about it). So i would like to ask, what would be a good approach ? Of course, i'm willing to study new things :)
Though a module may be ok, it does not feel too natural.
I'd say that for most Rubyists it does feel natural. In Ruby it's not that common to build complex hierarchy chains, with abstract classes and all that. Instead common functionality gets wrapped up in a module and included where needed. If I remember correctly "Eloquent Ruby" by Russ Olson treats this whole topic in a rather nice way and is generally a book I can't recommend enough to aspiring Ruby developers.
On the web there are quite a few good articles on mixins to get you started, I'll just give you the relevant link to the "Pickaxe":
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html
Why not use Concerns? Have a look here on how it's done.
Ruby has some nice support for delegation. You may want to use it if your module wants to store state information.
精彩评论