Polymorphism/Polymorphic Associations
Polymorphism / Polymorphic Associations
Polymorphism
Polymorphism = Send the same message to different objects and get different results.
Inheritance
class GenericParser
def parse
raise NotImplementedError, 'No method'
end
end
# inheritance 1
class JsonParser < GenericParser
def parse
puts 'JsonParser instance received a message.'
end
end
# inheritance 2
class XmlParser < GenericParser
def parse
puts 'XmlParser instance received a message.'
end
end
puts 'Using the XmlParser'
xml_parser = XmlParser.new
xml_parser.parse
puts 'Using the JsonParser'
json_parser = JsonParser.new
json_parser.parse
# Using the XmlParser
# XmlParser instance received a message.
# Using the JsonParser
# JsonParser instance received a message.Duck Typing
Decorator
https://robots.thoughtbot.com/back-to-basics-polymorphism-and-ruby#inheritance
Polymorphic Associations
A model can belong to more than one other model, on a single association.
Last updated
Was this helpful?