Module: Subroutine::Fields
Defined Under Namespace
Modules: ClassMethods
Instance Method Summary collapse
-
#field_provided?(key) ⇒ Boolean
check if a specific field was provided.
- #params_with_defaults ⇒ Object
- #sanitize_defaults ⇒ Object
-
#sanitize_params(inputs) ⇒ Object
if you want to use strong parameters or something in your form object you can do so here.
- #setup_fields(inputs = {}) ⇒ Object
Instance Method Details
#field_provided?(key) ⇒ Boolean
check if a specific field was provided
105 106 107 108 109 |
# File 'lib/subroutine/fields.rb', line 105 def field_provided?(key) return send(:"#{key}_field_provided?") if respond_to?(:"#{key}_field_provided?", true) @params.key?(key) end |
#params_with_defaults ⇒ Object
128 129 130 |
# File 'lib/subroutine/fields.rb', line 128 def params_with_defaults @defaults.merge(@params) end |
#sanitize_defaults ⇒ Object
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
# File 'lib/subroutine/fields.rb', line 132 def sanitize_defaults defaults = {}.with_indifferent_access _fields.each_pair do |field, config| next if config[:default].nil? deflt = config[:default] if deflt.respond_to?(:call) deflt = deflt.call elsif deflt.duplicable? # from active_support # Some classes of default values need to be duplicated, or the instance field value will end up referencing # the class global default value, and potentially modify it. deflt = deflt.deep_dup # from active_support end defaults[field] = ::Subroutine::TypeCaster.cast(deflt, config) end defaults end |
#sanitize_params(inputs) ⇒ Object
if you want to use strong parameters or something in your form object you can do so here. by default we just slice the inputs to the defined fields
113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/subroutine/fields.rb', line 113 def sanitize_params(inputs) out = {}.with_indifferent_access _fields.each_pair do |field, config| next unless inputs.key?(field) begin out[field] = ::Subroutine::TypeCaster.cast(inputs[field], config) rescue ::Subroutine::TypeCaster::TypeCastError => e raise ::Subroutine::TypeCaster::TypeCastError, "Error for field `#{field}`: #{e}" end end out end |
#setup_fields(inputs = {}) ⇒ Object
98 99 100 101 102 |
# File 'lib/subroutine/fields.rb', line 98 def setup_fields(inputs = {}) @original_params = inputs.with_indifferent_access @params = sanitize_params(@original_params) @defaults = sanitize_defaults end |