module ActionView module Helpers module JavaScriptMacrosHelper # Adds LOCAL autocomplete functionality to the text input field with the DOM ID specified by +field_id+. # This DOES NOT query the server via AJAX - it returns results from a pre-fetched javascript array. # # field_id:: The text field to auto-complete. # items:: An array of objects that will be turned into a javascript array. These items will be # mapped to an array of strings by calling item#field_id on each array item. To override, # specify the accessor method with the +:method+ option. # # Example: # # <%= local_auto_complete_field('name',@labels) %> => @labels.map { |label| label.name } # <%= local_auto_complete_field('name',@labels, :method => 'description') %> => @labels.map { |label| label.description } # # +options+ are: # # :auto_complete_results_id :: The element id of the DOM element containing the auto-complete results. # :method :: The method to call on +items+ to turn the array of +items+ into an array of strings. # # In addtion, options specific to the javascript functionality can be specified in +completion_options+. def local_auto_complete_field(field_id, items, options = {}, completion_options = {}) options = {:auto_complete_results_id => "#{field_id}_auto_complete", :method => field_id}.merge(options) completion_options = {:fullSearch => true, :frequency => 0, :minChars => 1, :skip_style => false}.merge(completion_options) html = (completion_options[:skip_style] ? "" : auto_complete_stylesheet) html << "
" html << javascript_tag("new Autocompleter.Local( '#{field_id}' , '#{options[:auto_complete_results_id]}', #{ generate_javascript_array(items,options[:method])}, #{completion_options.to_json} );") return html end private # Called by +#local_auto_complete_field+ to turn +items+ into a javascript array of strings. def generate_javascript_array(items,method) "[#{items.map { |item| item.send(method).gsub(/\A|\Z/, "'") }.join(',')}]" end end end end