Module: Cadmus::Slugs::HasSlug::ClassMethods

Defined in:
lib/cadmus/slugs.rb

Instance Method Summary collapse

Instance Method Details

#has_slug(options = {}) ⇒ Object

Sets up an automatic slug-generating field on this class. There is a slug field, which will store the resulting slug, and a slug generator field, which, if set, will automatically generate a slugified version of its content and store it in the slug field.

Additionally, +has_slug+ sets up a format validator for the slug field to ensure that it's a valid Cadmus slug, and defines +to_param+ to return the slug (so that links to the slugged object can use the slug in their URL).

+has_slug+ attempts to be smart about detecting when the user has manually set a slug for the object and not overwriting it. Auto-generated slugs are only used when there is not already a slug set.

Parameters:

  • options (Hash) (defaults to: {})

    options to override the default behavior.

Options Hash (options):

  • slug_field (Object)

    the name of the slug field. Defaults to +:slug+.

  • slug_generator_field (Object)

    the name of the slug generator field. Defaults to +:name+.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/cadmus/slugs.rb', line 50

def has_slug(options={})
  cattr_accessor :slug_field, :slug_generator_field
  
  self.slug_field = (options.delete(:slug_field) || :slug).to_s
  self.slug_generator_field = (options.delete(:slug_generator_field) || :name).to_s
  
  validates_format_of slug_field, :with => Cadmus::Slugs::SLUG_REGEX
  
  class_eval <<-EOF
  def #{slug_generator_field}=(new_value)
    write_attribute(:#{slug_generator_field}, new_value)
    if #{slug_field}.blank?
      self.#{slug_field} = Cadmus::Slugs.slugify(new_value)
      @auto_assigned_slug = true
    end
  end
  
  # If the user enters a title and no slug, don't overwrite the auto-assigned one
  def #{slug_field}=(new_slug)
    return if new_slug.blank? && @auto_assigned_slug
    write_attribute(:#{slug_field}, new_slug)
  end
  
  def to_param
    #{slug_field}
  end
  EOF
end