module Formalism::Form::Fields::ClassMethods
Module for class methods
Public Instance Methods
field(name, type = nil, **options)
click to toggle source
# File lib/formalism/form/fields.rb, line 31 def field(name, type = nil, **options) Coercion.new(type, options[:of]).check unless type.nil? fields_and_nested_forms[name] = options.merge(type: type) define_field_methods(name) end
fields_and_nested_forms()
click to toggle source
# File lib/formalism/form/fields.rb, line 27 def fields_and_nested_forms @fields_and_nested_forms ||= {} end
included(something)
click to toggle source
Calls superclass method
# File lib/formalism/form/fields.rb, line 15 def included(something) super fields_and_nested_forms.each do |name, options| if options.key?(:form) something.nested name, options[:form], **options else something.field name, options[:type], **options end end end
nested(name, form = nil, **options)
click to toggle source
# File lib/formalism/form/fields.rb, line 39 def nested(name, form = nil, **options) unless form || options.key?(:initialize) raise ArgumentError, 'Neither form class nor initialize block ' \ 'is not present' end fields_and_nested_forms[name] = options.merge(form: form) define_nested_form_methods(name) end
Private Instance Methods
define_field_methods(name)
click to toggle source
# File lib/formalism/form/fields.rb, line 59 def define_field_methods(name) module_for_accessors.instance_exec do define_method(name) { fields[name] } private define_method("#{name}=") do |value| options = self.class.fields_and_nested_forms[name] coerced_value = Coercion.new(*options.values_at(:type, :of)).result_for(value) fields[name] = coerced_value end end end
define_nested_form_methods(name)
click to toggle source
# File lib/formalism/form/fields.rb, line 74 def define_nested_form_methods(name) module_for_accessors.instance_exec do define_method("#{name}_form") { nested_forms[name] } define_method(name) { nested_forms[name].instance } end define_params_for_nested_method name end
define_params_for_nested_method(name)
click to toggle source
# File lib/formalism/form/fields.rb, line 84 def define_params_for_nested_method(name) params_method_name = "params_for_nested_#{name}" params_method_defined = method_defined?(params_method_name) || private_method_defined?(params_method_name) module_for_accessors.instance_exec do private define_method(params_method_name) { @params[name] } unless params_method_defined end end
module_for_accessors()
click to toggle source
# File lib/formalism/form/fields.rb, line 97 def module_for_accessors if const_defined?(:FieldsAccessors, false) mod = const_get(:FieldsAccessors) else mod = const_set(:FieldsAccessors, Module.new) include mod end mod end
remove_field(name)
click to toggle source
# File lib/formalism/form/fields.rb, line 52 def remove_field(name) fields_and_nested_forms.delete name undef_method name undef_method "#{name}=" end