#--
# Copyright (C) 2007 Dimitrij Denissenko
# Please read LICENSE document for more information.
#++
module SearchHelper
# Highlights the +words+ where they is found in the +text+ by surrounding it like
# I'm a highlight phrase. The highlighter can be specialized by
# passing +highlighter+ as single-quoted string with \1 where the phrase is supposed to be inserted.
# N.B.: The +words+ is sanitized to include only letters, digits, and spaces before use.
def highlight_search_terms(content, words, highlighter = '\1')
text, content_type = content
if content_type == 1
text = simple_markup(text)
elsif content_type == 2
text = markup(text)
end
text = strip_tags(text)
unless text.blank? || words.blank?
CGI::unescape(words) # url un-encode the params
results = []
words.gsub(/[\+\-\*]/, '').split(' ').each do |w|
regex = Regexp.escape(w)
arounds = text.split(%r{#{regex}}i)
text.scan(%r{#{regex}}i).each_with_index do |m, i|
before = arounds[i] || ''
after = arounds[i+1] || ''
results << if before.chars.size > 120
'...' + before.last(120).gsub(%r{^[^\s]+}, '')
elsif i == 0
before
end
results << content_tag('span', m, :class => 'highlight')
results << if after.chars.size > 120
after.first(120).gsub(%r{[^\s]+$}, '') + ' ...
'
else
after
end
end
end
text = results.blank? ? truncate(text, 120) : results.join('')
end
text
end
def result_link(result)
caption = truncate(result.previewable.title, 100)
options = result.previewable.permalink_options
link_to(caption, options)
end
def search_type_checkboxes
checkboxes = []
check_all = params[:all] == '1' || !params.has_key?(:q)
opts = { :id => 'search_type_all' }
label = content_tag :label, _('All'), :for => opts[:id], :class => 'inline'
checkboxes << check_box_tag('all', 1, check_all, opts) + " #{label}"
@searchable_classes.each do |klass|
name = klass.table_name
opts = {
:id => 'search_type_' + name,
:onclick => "if (this.checked) $('search_type_all').checked = false;"
}
label = content_tag :label, _("#{name.humanize}"), :for => opts[:id], :class => 'inline'
checkboxes << check_box_tag(name, 1, params[name] == '1', opts) + " #{label}"
end
row_num = (checkboxes.size.to_f / 6).ceil
per_row = (checkboxes.size.to_f / row_num).ceil
rows = []
while rows.size < row_num
rows << checkboxes[rows.size * per_row, per_row].join(' ')
end
rows.join('
')
end
end