Module: HasFriendlyName::ClassMethods

Defined in:
lib/has_friendly_name.rb

Instance Method Summary collapse

Instance Method Details

#find_by_friendly_name(query, options = {}) ⇒ Object

Raises:

  • (ActiveRecord::RecordNotFound)


20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/has_friendly_name.rb', line 20

def find_by_friendly_name(query, options={})
  obj = find(:first, :conditions => "friendly_name ='#{query}'")
  
  if query.match(/\d+/) and !options[:exact]
    obj = find(:first, :conditions => "friendly_name = '#{query.gsub(/-\d+/, "")}'") unless obj
    obj = find(:first, :conditions => "friendly_name LIKE '#{query.gsub(/-\d+/, "")}-%'") unless obj
  end
  
    
  raise ActiveRecord::RecordNotFound, "Couldn't find #{name} with friendly_name #{query}" unless obj

  obj
end

#has_friendly_name(options = {}) ⇒ Object

adds friendly_name to your model. Options are:

  • unique => boolean - should the friendly_name be unique for this model? appends count if name has been taken

  • to_downcase - friendly_name will be downcased

  • titelize - friendly_name will be titelized



13
14
15
16
17
18
# File 'lib/has_friendly_name.rb', line 13

def has_friendly_name(options={})
  self.cattr_accessor :has_friendly_name_options
  self.has_friendly_name_options = {:unique => true, :titelize => false, :downcase => true, :from => :name}.merge(options)
  before_create :generate_friendly_name
  include HasFriendlyName::InstanceMethods
end