Module: Acts::Slugoid::ClassMethods

Defined in:
lib/slugoid/acts/slugoid.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_slugoid(options = {}) ⇒ Object

Adds the logic to generate the slug

Options:

:generate_from
    The name of the field used to generate the slug

:store_as
    The name of the field where the slug will be stored


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/slugoid/acts/slugoid.rb', line 15

def acts_as_slugoid(options = {})
@acts_as_slugoid_options = {
  :generate_from => :name,
  :store_as => :slug
  }.merge(options)

  generate_from = @acts_as_slugoid_options[:generate_from]
  store_as = @acts_as_slugoid_options[:store_as]

  class_eval do
    before_save do
      generate_slug(generate_from, store_as)
    end

    field(store_as, :type => String) unless self.respond_to?(store_as)
    index(store_as)
    alias_method :to_param!, :to_param

    include InstanceMethods

    def self.acts_as_slugoid_options
      @acts_as_slugoid_options
    end

    def self.find_by_slug(slug)
      where(@acts_as_slugoid_options[:store_as] => slug).first
    end
  end

  define_method("to_param") do
    self.send(store_as)
  end
end