Question

I'm using STI for a project where I'd like each model to have a method that returns a hash. That hash is a specific profile for that model. I'd like each child model to retrieve its parent's hash and add it to its own. Here's an example below

class Shape
 include Mongoid::Document
 field :x, type: Integer
 field :y, type: Integer
 embedded_in :canvas

 def profile
   { properties: {21} }
 end
end



class Rectangle < Shape
 field :width, type: Float
 field :height, type: Float

 def profile
   super.merge({ location: {32} })
 end
end

I'm trying to figure out how to get Rectangle's profile method to return Shape's + its own. It should result in

(properties => 21, location => 32)

Any idea how to access the parent from the inherited child? Is it just super? Been stuck on this for the last couple days. Any help much appreciated!

Was it helpful?

Solution

Yes, it's that simple. :-) You've just got a couple of improper literals in {21} and {32}.

The following works:

class Shape

 def profile
   { properties: 21 }
 end
end


class Rectangle < Shape

 def profile
   super.merge({ location: 32 })
 end
end

rect = Rectangle.new
puts rect.profile # => {:properties => 21, :location => 32}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top