Search code examples
ruby-on-railsmodelmixins

Mixin for similar Rails models


I'm not quite a Rails novice, but I'm certainly a long way from being an expert. I understand how modules work in a general sense, but I've never quite understood how I can use my own self-created modules to my advantage. This is a pretty simple example where I'm pretty sure a mixin module would be appropriate and useful.

My Rails application models association football (soccer) matches. Matches are represented by a Match model. I have several more models to represent events which might occur during a match (e.g. Goal, PenaltyKick, Caution). The Match model and the models for these events have a has_many/belongs_to relationship.

Each of these models has three temporal attributes in common: period, minute, and order_within_minute. With the information in these columns, I can write a pretty simple <=> method to make these events comparable based on when they happen. It is crucial that I be able to compare the events on this basis so that I can return a sorted list of events within a match.

I understand that each of these models needs to include identical code in order to achieve what I want:

include Comparable

def <=>
  ## Comparison code goes here ##
end

It would seem to me that this can be accomplished with a mixin to apply that same bit of code to each of these models, but I'm not quite sure how to go about doing that.

I realize this is probably a really basic question, but what's the right way to do this? Do I put the above block of code within a module and include that module in each of these models, or do I need to do something different? Where do I put this code within my file system?


Solution

  • Do I put the above block of code within a module and include that module in each of these models, or do I need to do something different?

    That's exactly what you do.

    Where do I put this code within my file system?

    It should be fine living under comparable.rb in app/models/concerns, even though it doesn't make use of the syntactic sugar that ActiveSupport::Concern offers.