Search code examples
ruby-on-railsdrydelegation

Sharing delegation methods between two models


Model A and Model B share the following delegation methods:

  delegate :league, :to => :event, :prefix => true, :allow_nil => false # event_league

  def event_league_sport
    self.event_league.sport
  end

  def event_league_sport_name
    event_league_sport.name
  end

So that I don't have to repeat the same methods in each class, what's the best way to share them between the two in a nice DRY way?


Solution

  • Add the methods to a module and include said module in your classes:

    module EventDelegator
      def event_league_sport
        self.event_league.sport
      end
    
      def event_league_sport_name
        event_league_sport.name
      end
    end
    
    class A
      include EventDelegator
    end