Skip to content

Commit

Permalink
Refactor FormHelper#search_form_for
Browse files Browse the repository at this point in the history
- Extract code into smaller, private methods for readability and
maintainability.

- Avoid hidden conditionals and ternaries to keep conditionals as
explicit (and painful) as possible.

- Use Ruby 1.9+ hash syntax.
  • Loading branch information
jonatack committed Jul 26, 2015
1 parent 17dd97a commit 29a73b9
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions lib/ransack/helpers/form_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,17 @@ def search_form_for(record, options = {}, &proc)
elsif record.is_a?(Array) &&
(search = record.detect { |o| o.is_a?(Ransack::Search) })
options[:url] ||= polymorphic_path(
record.map { |o| o.is_a?(Ransack::Search) ? o.klass : o },
format: options.delete(:format)
options_for(record), format: options.delete(:format)
)
else
raise ArgumentError,
'No Ransack::Search object was provided to search_form_for!'
end
options[:html] ||= {}
html_options = {
:class => options[:class].present? ?
"#{options[:class]}" :
"#{search.klass.to_s.underscore}_search",
:id => options[:id].present? ?
"#{options[:id]}" :
"#{search.klass.to_s.underscore}_search",
:method => :get
class: html_option_for(options[:class], search),
id: html_option_for(options[:id], search),
method: :get
}
options[:as] ||= Ransack.options[:search_key]
options[:html].reverse_merge!(html_options)
Expand All @@ -54,6 +49,26 @@ def sort_link(search_object, attribute, *args)

private

def options_for(record)
record.map &method(:parse_record)
end

def parse_record(object)
if object.is_a?(Ransack::Search)
object.klass
else
object
end
end

def html_option_for(option, search)
if option.present?
option.to_s
else
"#{search.klass.to_s.underscore}_search"
end
end

def extract_search_and_routing_proxy(search)
if search.is_a? Array
[search.second, search.first]
Expand Down

0 comments on commit 29a73b9

Please sign in to comment.