Module: DataMapper::Is::Slug

Defined in:
lib/dm-is-slug/is/slug.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods Classes: InvalidSlugSourceError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.escape(str) ⇒ String

Returns an URL-safe string.

Parameters:

  • str (String)

    A string to escape for use as a slug

Returns:

  • (String)

    an URL-safe string



17
18
19
20
21
22
23
24
# File 'lib/dm-is-slug/is/slug.rb', line 17

def self.escape(str)
  s = str.to_ascii
  s.gsub!(/\W+/, ' ')
  s.strip!
  s.downcase!
  s.gsub!(/\ +/, '-')
  s
end

.included(base) ⇒ Object



9
10
11
# File 'lib/dm-is-slug/is/slug.rb', line 9

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#is_slug(options) ⇒ Object

Defines a slug property on your model with the same length as your source property. This property is Unicode escaped, and treated so as to be fit for use in URLs.

Example

Suppose your source attribute was the following string: “Hot deals on Boxing Day”. This string would be escaped to “hot-deals-on-boxing-day”.

Non-ASCII characters are attempted to be converted to their nearest approximate.

Parameters

permanent_slug

Permanent slugs are not changed even if the source property has

source

The property on the model to use as the source of the generated slug, or an instance method defined in the model, the method must return a string or nil.

length

The length of the slug property

Parameters:

  • provide (Hash)

    options in a Hash. See Parameters for details

Raises:



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/dm-is-slug/is/slug.rb', line 55

def is_slug(options)
  if options.key?(:size)
    warn "Slug with :size option is deprecated, use :length instead"
    options[:length] = options.delete(:size)
  end

  extend  DataMapper::Is::Slug::ClassMethods
  include DataMapper::Is::Slug::InstanceMethods
  extend Chainable

  @slug_options = {}

  @slug_options[:permanent_slug] = options.delete(:permanent_slug)
  @slug_options[:permanent_slug] = true if @slug_options[:permanent_slug].nil?

  if options.has_key? :scope
    @slug_options[:scope] = [options.delete(:scope)].flatten
  end

  @slug_options[:unique] = options.delete(:unique) || false

  @slug_options[:source] = options.delete(:source)
  raise InvalidSlugSourceError, 'You must specify a :source to generate slug.' unless slug_source


  options[:length] ||= get_slug_length
  if slug_property && slug_property.class >= DataMapper::Property::String
      options.merge! slug_property.options
  end
  property :slug, String, options

  if @slug_options[:unique]
    scope_options = @slug_options[:scope] && @slug_options[:scope].any? ?
      {:scope => @slug_options[:scope]} : {}

    validates_uniqueness_of :slug, scope_options
  end

  before :valid?, :generate_slug
end