Class: WebfaceForm

Inherits:
Object
  • Object
show all
Defined in:
app/helpers/webface_form.rb

Defined Under Namespace

Classes: NoSuchFormFieldType

Constant Summary collapse

OPTION_ATTRS =
[:tabindex, :label, :suffix, :selected, :hint, :collection, :allow_custom_value, :fetch_url, :query_param_name, :disabled, :nested_field, :serialized_hash, :model_field_name, :model_name, :radio_options_id, :popup_hint, :has_blank]

Instance Method Summary collapse

Constructor Details

#initialize(model, view_context) ⇒ WebfaceForm

Returns a new instance of WebfaceForm.



7
8
9
10
11
# File 'app/helpers/webface_form.rb', line 7

def initialize(model, view_context)
  @model         = model
  @view_context  = view_context
  @field_counter = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args) ⇒ Object



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
# File 'app/helpers/webface_form.rb', line 13

def method_missing(m, *args)

  attrs   = {}
  options = {}
  if args.last.kind_of?(Hash)
    attrs   = args.last
    options = separate_option_attrs(attrs)
  end
  field_type = m

  unless self.class.private_method_defined?("_#{field_type}")
    raise NoSuchFormFieldType, "Field type `#{field_type}` not supported"
  end

  field_name = if args.first.blank? || args.first.to_s =~ /!\Z/
    args.first.to_s.sub("!", "")
  else
    "#{@model.class.to_s.underscore}[#{args.first}]"
  end

  if options[:nested_field]
    field_name = modify_name_for_nested_field(field_name, options[:nested_field])
  elsif args.first && args.first.to_s.include?("[") && options[:nested_field].nil?
    field_name = modify_name_for_serialized_field(field_name)
  end

  if @field_counter[field_name]
    @field_counter[field_name] += 1
  else
    @field_counter[field_name] = 0
  end
  options[:field_counter] = @field_counter[field_name]

  options[:radio_options_id] = options[:name] if options[:name]

  options.merge!({ name: field_name, attr_name: args.first, model: @model, model_name: self.model_name})
  attrs.delete_if { |k,v| OPTION_ATTRS.include?(k) }
  attrs.merge!({ options: options })

  if attrs[:options][:label].nil?
    attrs[:options][:label] = I18n.t("models.#{field_name_for_i18n(field_name)}")
  end

  self.send("_#{field_type}", attrs)
end

Instance Method Details

#model_nameObject



59
60
61
62
63
64
65
# File 'app/helpers/webface_form.rb', line 59

def model_name
  if @model
    @model.class.to_s.underscore
  else
    options[:name].split("[").first
  end
end