Module: SluggableFinder::Orm::ClassMethods

Defined in:
lib/sluggable_finder/orm.rb

Instance Method Summary collapse

Instance Method Details

#sluggable_finder(field = :title, options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/sluggable_finder/orm.rb', line 6

def sluggable_finder(field = :title, options = {})
  return if self.included_modules.include?(SluggableFinder::Orm::InstanceMethods)
  extend SluggableFinder::Finder
  extend SluggableFinder::BaseFinder
  include SluggableFinder::Orm::InstanceMethods

  class << self
    alias_method_chain :find, :slug
  end
  
  write_inheritable_attribute(:sluggable_finder_options, {
    :sluggable_type => ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s,
    :from		        =>	field,
  	:scope		      => 	nil,
  	:to			        =>  :slug,
  	:reserved_slugs => []
  }.merge( options ))
  class_inheritable_reader :sluggable_finder_options

  if sluggable_finder_options[:scope]
    scope_condition_method = %(
      def scope_condition
          "#{sluggable_finder_options[:scope].to_s} = \#{#{sluggable_finder_options[:scope].to_s}}"
      end
    )
  else
    scope_condition_method = %(
      def scope_condition 
        '1 = 1'
      end
    )
  end

  class_eval <<-EOV

    def slugable_class
      ::#{self.name}
    end

    def source_column
      "#{sluggable_finder_options[:from]}"
    end

    def destination_column
      "#{sluggable_finder_options[:to]}"
    end

    def to_param
    	self.#{sluggable_finder_options[:to]}
    end

    #{scope_condition_method}

    after_validation :set_slug
  EOV

end