Search code examples
ruby-on-railsrubymodulefriendly-urlfriendly-id

Using FriendlyId inside a module


I'm using FriendlyId across many of my models. I noticed some redundancy in my code as far as creating functionality for updating urls so I decided to put it in a module:

module TestModule
  def should_generate_new_friendly_id?
    name_changed?
  end
end

The problem now is if I take the essential line of code needed to create the slugs out of my classes and into my module

extend FriendlyId; friendly_id :name, use: :slugged

I get this error:

undefined method `relation' for class `Module'

Is there any way to get this to work without me having to right the extend declaration for every one of my models?


Solution

  • You can let your module extend the friendly for the classes you include it in.

    module TestModule
      def self.included(klass)
        klass.extend FriendlyId
        klass.class_eval do
          friendly_id :name, use: :slugged
        end
        include InstanceMethods
      end
      module InstanceMethods
        def should_generate_new_friendly_id?
          name_changed?
        end
      end
    end
    

    Then in your model you'll just include this

    class MyModel < ActiveRecord::Base
      include TestModule
      # the rest of the class
    end
    

    Also you could do it without the extra module

    module TestModule
      def self.included(klass)
        klass.extend FriendlyId
        klass.class_eval do
          friendly_id :name, use: :slugged
          def should_generate_new_friendly_id?
            name_changed?
          end
        end
      end
    end