10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
# File 'lib/sluggable_rubby.rb', line 10
def has_slug(*attributes, scope: nil)
before_validation :generate_slug
validates :slug, presence: true, uniqueness: { scope: scope }
define_singleton_method :find_by_slug do |slug|
find_by(slug: slug)
end
define_method(:generate_slug) do
return unless attributes.any? { |attr| !send(attr).nil? }
base_slug = attributes.map { |attr| send(attr).to_s.parameterize }.join('-').truncate(100, omission: '').downcase
self.slug = self.class.unique_slug(base_slug, scope, scope ? self.send(scope) : nil)
end
end
|