Sha256: af8fda28af884d9e2d2bcf9002d14e7edbe2e9ebd3b2b5802946d8fe2adfc5a6

Contents?: true

Size: 1.79 KB

Versions: 9

Compression:

Stored size: 1.79 KB

Contents

require 'stringex'

module Spree
  module Core
    module Permalinks
      extend ActiveSupport::Concern

      included do
        class_attribute :permalink_options
      end

      module ClassMethods
        def make_permalink(options={})
          options[:field] ||= "permalink"
          self.permalink_options = options

          validates_uniqueness_of permalink_options[:field]

          if self.table_exists? && self.column_names.include?(permalink_options[:field].to_s)
            before_validation(:on => :create) { save_permalink }
          end
        end

        def find_by_param(value, *args)
          self.send("find_by_#{permalink_field}", value, *args)
        end

        def find_by_param!(value, *args)
          self.send("find_by_#{permalink_field}!", value, *args)
        end

        def permalink_field
          permalink_options[:field]
        end

      end

      module InstanceMethods
        def save_permalink
          permalink_value = self.to_param
          field = self.class.permalink_field
          # Do other links exist with this permalink?
          other = self.class.first(
            :conditions => "#{field} LIKE '#{permalink_value}%'",
            :order => "LENGTH(#{field}) DESC, #{field} DESC"
          )
          if other
            # Find the number of that permalink and add one.
            if /-(\d+)$/.match(other.send(field))
              number = $1.to_i + 1
            # Otherwise default to suffixing it with a 1.
            else
              number = 1
            end

            permalink_value += "-#{number.to_s}"
          end
          write_attribute(field, permalink_value)
        end

      end
    end
  end
end

ActiveRecord::Base.send :include, Spree::Core::Permalinks
ActiveRecord::Relation.send :include, Spree::Core::Permalinks

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
spree_core-1.0.7 lib/spree/core/permalinks.rb
spree_core-1.0.6 lib/spree/core/permalinks.rb
spree_core-1.0.4 lib/spree/core/permalinks.rb
spree_core-1.0.3 lib/spree/core/permalinks.rb
spree_core-1.0.2 lib/spree/core/permalinks.rb
spree_core-1.0.1 lib/spree/core/permalinks.rb
spree_core-1.0.0 lib/spree/core/permalinks.rb
spree_core-1.0.0.rc4 lib/spree/core/permalinks.rb
spree_core-1.0.0.rc3 lib/spree/core/permalinks.rb