Module: Formidable::Coercions
- Included in:
- Elements::Element
- Defined in:
- lib/formidable/coercions.rb
Constant Summary collapse
- MissingCoercion =
Class.new(StandardError)
- IncompatibleInterface =
Class.new(StandardError)
Class Method Summary collapse
Instance Method Summary collapse
Class Method Details
.coercions ⇒ Object
8 9 10 11 12 |
# File 'lib/formidable/coercions.rb', line 8 def self.coercions @coercions ||= Hash.new do |hash, key| raise MissingCoercion, "No coercion defined for #{key}" end end |
.included(klass) ⇒ Object
18 19 20 21 22 |
# File 'lib/formidable/coercions.rb', line 18 def self.included(klass) if ! klass.method_defined?(:raw_data) || ! klass.method_defined?(:cleaned_data=) raise IncompatibleInterface, "You are supposed to define #{klass}#raw_data and #{klass}#cleaned_data= in order to get coercions running!" end end |
Instance Method Details
#cleaned_data ⇒ Object
24 25 26 |
# File 'lib/formidable/coercions.rb', line 24 def cleaned_data @cleaned_data ||= self.coerce! end |
#coerce(type = nil, &block) ⇒ Object
32 33 34 35 36 37 38 39 40 |
# File 'lib/formidable/coercions.rb', line 32 def coerce(type = nil, &block) if type && block.nil? coercions << Coercions.coercions[type] elsif type.nil? && block coercions << block else raise ArgumentError, "provide block or type" end end |
#coerce! ⇒ Object
42 43 44 45 46 47 48 |
# File 'lib/formidable/coercions.rb', line 42 def coerce! self.cleaned_data = begin coercions.inject(self.raw_data) do |coercion, raw_data| coercion.call(raw_data) end end end |
#coercions ⇒ Object
28 29 30 |
# File 'lib/formidable/coercions.rb', line 28 def coercions @coercions ||= Array.new end |