Class: ActiveRecord::Base

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

Class Method Summary collapse

Class Method Details

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

Add association by autocomplete field in post.rb add_by_autocomplete(‘user’, ‘name) for has_many() association, like on github’s collaborators search in user.rb add find_by_autocomplete :name Post.first.add_bu_auto_user_name=(value) will be resolved to a User, using User.find_by_autocomplete_name(value)



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/simple_autocomplete.rb', line 59

def self.add_by_autocomplete(model, attribute, options={})
  model, name = autocomplete_model_and_name(model, options[:name])
  finder = autocomplete_finder_for(model, attribute)

  #add_user_by_autocomplete= "Hans"
  define_method "add_by_auto_#{name}_#{attribute}=" do |value|
    send(name.pluralize).send('<<', model.send(finder, value)) if value and !value.empty?
  end

  # avoid method missing error when rendering a form field
  define_method("add_by_auto_#{name}_#{attribute}"){}
end

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

Store autocomplete field as association in post.rb: autocomplete_for(‘user’, ‘name’) in user.rb add find_by_autocomplete :name Post.first.auto_user_name=(value) will be resolved to a User, using User.find_by_autocomplete_name(value)



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/simple_autocomplete.rb', line 40

def self.autocomplete_for(model, attribute, options={})
  model, name = autocomplete_model_and_name(model, options[:name])
  finder = autocomplete_finder_for(model, attribute)

  #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(attribute) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/simple_autocomplete.rb', line 72

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