简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM