views:

223

answers:

1

I have a series of models all which inherit from a base model Properties

For example Bars, Restaurants, Cafes, etc.

class Property
  include MongoMapper::Document

  key :name, String
  key :_type, String
end

class Bar < Property

What I'm wondering is what to do with the case when a record happens to be both a Bar & a Restaurant? Is there a way for a single object to inherit the attributes of both models? And how would it work with the key :_type?

+1  A: 

I think you want a module here.

class Property
  include MongoMapper::Document

  key :name, String
  key :_type, String
end

module Restaurant
  def serve_food
    puts 'Yum!'
  end
end

class Bar < Property
  include Restaurant
end

Bar.new.serve_food # => Yum!

This way you can let many models have the properties of a restaurant, without duplicating your code.

What you could also try, though I haven't experimented with it myself, is multiple levels of inheritance. e.g.:

class Property
  include MongoMapper::Document

  key :name, String
  key :_type, String
end

class Restaurant < Property
  key :food_menu, Hash
end

class Bar < Restaurant
  key :drinks_menu, Hash
end

Not sure off the top of my head whether MongoMapper supports this, but I don't see why it wouldn't.

PreciousBodilyFluids
Its not that the models inherit other models, I understand how to do that, what I'm wondering about are special cases where a particular record behaves like a hybrid between two models.
holden
That would be the case in my last example - a saved bar record would have both a food_menu and a drinks_menu. Did you mean something different?
PreciousBodilyFluids