Module: HasSlug::ClassMethods

Defined in:
lib/has_slug.rb

Constant Summary collapse

VALID_HAS_SLUG_OPTIONS =

Valid options for the has_slug method

[:scope, :slug_column, :preserve].freeze
DEFAULT_HAS_SLUG_OPTIONS =

Default options for the has_slug method

{ :scope => nil, :slug_column => 'slug', :preserve => '' }.freeze

Instance Method Summary collapse

Instance Method Details

#has_slug(attribute, options = {}) ⇒ Object

Set up an ActiveRecord model to use a slug.

The attribute argument can be one of your model’s columns, or a method you use to generate the slug.

Options:

  • :scope - The scope of the slug

  • :slug_column - The column that will be used to store the slug in (defaults to slug)



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/has_slug.rb', line 39

def has_slug(attribute, options = {})
  options.assert_valid_keys(VALID_HAS_SLUG_OPTIONS)
  
  options = DEFAULT_HAS_SLUG_OPTIONS.merge(options).merge(:attribute => attribute)
  
  if defined?(has_slug_options)
    Rails.logger.error "has_slug_options is already defined, you can only call has_slug once. This call has been ignored."
  else
    write_inheritable_attribute(:has_slug_options, options)
    class_inheritable_reader(:has_slug_options)

    if columns.any? { |column| column.name.to_s == options[:slug_column].to_s }
      require 'has_slug/sluggable_class_methods'
      require 'has_slug/sluggable_instance_methods'

      extend SluggableClassMethods
      include SluggableInstanceMethods

      before_save :set_slug,
                  :if => :new_slug_needed?
    else
      require 'has_slug/not_sluggable_class_methods'
      require 'has_slug/not_sluggable_instance_methods'

      extend NotSluggableClassMethods
      include NotSluggableInstanceMethods
    end        
  end
end