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)



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/has_slug.rb', line 30

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)
    raise Exception, "has_slug_options is already defined, you can only call has_slug once"
  end
  
  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