Module: ChinaRegions::Helpers::FormHelper

Defined in:
lib/china_regions/helpers/form_helper.rb

Instance Method Summary collapse

Instance Method Details

#region_select(object_name, fields, options = {}, html_options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/china_regions/helpers/form_helper.rb', line 6

def region_select(object_name, fields, options = {}, html_options = {})
  output = []

  preselected_choices = setup_regions_options(options)

  html_options[:class] ?
    html_options[:class].prepend('region_select ') :
      (html_options[:class] = 'region_select')

  dropdown_prefix = options[:prefix] ? options[:prefix].to_s + '_' : ''

  if fields.is_a?(Array)
    fields.each_with_index do |field, field_index|
      if region_klass = field.to_s.classify.safe_constantize
        choices = fetch_choices(region_klass, field, preselected_choices, field_index)
        choices = prioritize_choices(options[:priority][field], choices) if options[:priority].try(:[], field)

        next_method = fields.at(field_index + 1)

        set_prompt(field, options, region_klass)
        set_html_options(object_name, field, html_options, next_method, dropdown_prefix)

        if options[:default] && options[:default][field]
          options[:selected] = options[:default][field] if options[:default][field]
        end

        output << select(object_name, "#{dropdown_prefix}#{field}_id", choices, options, html_options)
      else
        raise "Method '#{field}' is not a vaild attribute of #{object_name}"
      end
    end
  else
    inner_methods = if fields.to_s.include?('_id')
      inner_methods = fields
      fields = fields.to_s.gsub(/(_id)$/, '')
      inner_methods
    else
      (fields.to_s + '_id').to_sym
    end

    if region_klass = fields.to_s.classify.safe_constantize
      options[:prompt] = region_prompt(region_klass)
      options[:selected] = preselected_choices[:province_id] if fields == :province && preselected_choices[:province_id]

      output << select(object_name, inner_methods, region_options(region_klass), options: options, html_options: html_options)
    else
      raise "Method '#{fields}' is not a vaild attribute of #{object_name}"
    end
  end
  output.join.html_safe
end