Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_autocomplete.rb

Overview

Store the value of the autocomplete field as association autocomplete_for(‘user’,‘name’) -> the auto_user_name field will be resolved to a User, using User.find_by_autocomplete_name(value) -> Post has autocomplete_for(‘user’,‘name’) -> User has find_by_autocomplete(‘name’) see Readme for more details

Class Method Summary collapse

Class Method Details

.autocomplete_for(model, attribute, options = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/simple_autocomplete.rb', line 41

def self.autocomplete_for(model, attribute, options={})
  name = options[:name] || model.to_s.underscore
  name = name.to_s
  model = model.to_s.camelize.constantize

  # is the correct finder defined <-> warn users
  finder = "find_by_autocomplete_#{attribute}"
  unless model.respond_to? finder
    raise "#{model} does not respond to #{finder}, maybe you forgot to add auto_complete_for(:#{attribute}) to #{model}?"
  end

  #auto_user_name= "Hans"
  define_method "auto_#{name}_#{attribute}=" do |value|
    send "#{name}=", model.send(finder, value)
  end

  #auto_user_name
  define_method "auto_#{name}_#{attribute}" do
    send(name).try(:send, attribute).to_s
  end
end

.find_by_autocomplete(attr) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/simple_autocomplete.rb', line 63

def self.find_by_autocomplete(attr)
  metaclass = (class << self; self; end)
  metaclass.send(:define_method, "find_by_autocomplete_#{attr}") do |value|
    return if value.blank?
    self.first(:conditions => [ "LOWER(#{attr}) = ?", value.to_s.downcase ])
  end
end