Module: ChinaRegions::Helpers::FormHelper

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

Instance Method Summary collapse

Instance Method Details

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



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
57
58
# File 'lib/china_regions/helpers/form_helper.rb', line 7

def region_select(object_name, methods, 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 Array == methods
    methods.each_with_index do |method, index|
      if region_klass = method.to_s.classify.safe_constantize
        choices = fetch_choices(region_klass, method, preselected_choices, index)
        choices = prioritize_choices(options[:priority][method], choices) if options[:priority].try(:[], method)

        next_method = methods.at(index + 1)

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

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

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

    if region_klass = methods.to_s.classify.safe_constantize
      options[:prompt] = region_prompt(region_klass)

      options[:selected] = preselected_choices[:province_id] if methods == :province && preselected_choices[:province_id]

      output << select(object_name, inner_methods, region_klass.where(nil).collect { |p| [p.name, p.id] }, options = options, html_options = html_options)
    else
      raise "Method '#{method}' is not a vaild attribute of #{object_name}"
    end
  end
  output.html_safe
end