Sha256: 8f116ee315fd1571d993451078351418fb462fb8fe2a175538b1c916b0fdc031

Contents?: true

Size: 1.1 KB

Versions: 7

Compression:

Stored size: 1.1 KB

Contents

require 'active_support/concern'

module Georgia
  module Concerns
    module Slugable
      extend ActiveSupport::Concern

      included do

        attr_accessible :slug, :url

        validates :slug, format: {with: /^[a-zA-Z0-9_-]+$/,  message: 'can only consist of letters, numbers, dash (-) and underscore (_)'}#, uniqueness: {scope: [:ancestry, :type], message: 'has already been taken'}

        before_validation :sanitize_slug
        after_save :update_url

        # Must stay public for #update_url on descendants
        def set_url
          self.update_column(:url, '/' + self.ancestry_url)
        end

        protected

        def sanitize_slug
          self.slug ||= ''
          self.slug.gsub!(/^\/*/, '').gsub!(/\/*$/, '')
        end

        def update_url
          if slug_changed? or ancestry_changed?
            self.set_url
            self.descendants.each(&:set_url) if !self.new_record? and self.has_children?
          end
        end

        def ancestry_url
          (ancestors + [self]).map(&:slug).join('/')
        end

      end

      module ClassMethods
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
georgia-0.7.6 app/models/georgia/concerns/slugable.rb
georgia-0.7.5 app/models/georgia/concerns/slugable.rb
georgia-0.7.4 app/models/georgia/concerns/slugable.rb
georgia-0.7.3 app/models/georgia/concerns/slugable.rb
georgia-0.7.2 app/models/georgia/concerns/slugable.rb
georgia-0.7.1 app/models/georgia/concerns/slugable.rb
georgia-0.7.0 app/models/georgia/concerns/slugable.rb