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
-
.escape(str) ⇒ String
An URL-safe string.
- .included(base) ⇒ Object
Instance Method Summary collapse
-
#is_slug(options) ⇒ Object
Defines a
slug
property on your model with the same length as your source property.
Class Method Details
.escape(str) ⇒ String
Returns 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
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() if .key?(:size) warn "Slug with :size option is deprecated, use :length instead" [:length] = .delete(:size) end extend DataMapper::Is::Slug::ClassMethods include DataMapper::Is::Slug::InstanceMethods extend Chainable @slug_options = {} @slug_options[:permanent_slug] = .delete(:permanent_slug) @slug_options[:permanent_slug] = true if @slug_options[:permanent_slug].nil? if .has_key? :scope @slug_options[:scope] = [.delete(:scope)].flatten end @slug_options[:unique] = .delete(:unique) || false @slug_options[:source] = .delete(:source) raise InvalidSlugSourceError, 'You must specify a :source to generate slug.' unless slug_source [:length] ||= get_slug_length if slug_property && slug_property.class >= DataMapper::Property::String .merge! slug_property. end property :slug, String, if @slug_options[:unique] = @slug_options[:scope] && @slug_options[:scope].any? ? {:scope => @slug_options[:scope]} : {} validates_uniqueness_of :slug, end before :valid?, :generate_slug end |