Sha256: 17a60df1dda81d22131d97529e6e5c088da8ade0a8bfe1d8091720acee931274

Contents?: true

Size: 993 Bytes

Versions: 2

Compression:

Stored size: 993 Bytes

Contents

module PrettyUrl
  extend ActiveSupport::Concern

  included do
    after_save :update_url_name
  end

  module ClassMethods
    def find(id)
      if id.is_a?(String)
        real_id = /(.*\-)?(?<id>\d+)\Z/.match(id)[:id]
      else
        real_id = id
      end
      super(real_id)
    end
  end

  def to_param
    url_name
  end

  private
  def update_url_name
    if I18n.locale == :en
      if self.has_attribute?(:name)
        self.update_column :url_name, "#{name.to_url}-#{id}"

      elsif self.has_attribute?(:title)
        self.update_column :url_name, "#{title.to_url}-#{id}"

      elsif self.translations.first.has_attribute?(:name)
        self.update_column :url_name, "#{name.to_url}-#{id}"

      elsif self.translations.first.has_attribute?(:title)
        self.update_column :url_name, "#{title.to_url}-#{id}"

      else
        self.update_column :url_name, self.id
      end
    elsif url_name.blank?
      self.update_column :url_name, self.id
    end
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
tmatt_cms-0.1.9 lib/generators/tmatt_cms/templates/concerns/pretty_url.rb
tmatt_cms-0.1.8 lib/generators/tmatt_cms/templates/concerns/pretty_url.rb