This is a Rails 3 application.
I have images that can be tied to either a Product or a Brand. A product has an identifier and a Brand has a name.
The polymorphic relationship from Image is called “linkable”.
If I want to list the items that a particular image is linked to, I want to avoid doing a conditional in the view like this:
<% for image in Image.all %>
<% if image.linkable.class.name=="Product" %>
<%= image.linkable.identifier %>
<% elsif image.linkable.class.name=="Brand" %>
<%= image.linkable.name %>
<% end %>
<% end %>
Of course I could just put a method inside Brand called “identifier” and use it to call “name”. But that’s not extensible if i want to add more objects that an image can be linked to. 8 years ago in Java programming I could mandate that a class implemented an Interface, but I don’t know if I can do anything like that in Ruby. I appreciate any guidance anybody can offer.
You could create a module called Linkable and create the behavior methods in that. Then you extend the module in the classes where you want to add those behaviors. This way you don’t have to worry about inheriting from anything you can just mix-in the behavior.
This is the standard Ruby way of adding common functionality to multiple classes without inheriting. You would also, by convention, name your module using a verb based adjective instead of a verb; Linkable vs. Link.
For instance:
Of course your classes and the module will have actual functionality.