Module: Organ::Coercer
- Included in:
- Form
- Defined in:
- lib/organ/coercer.rb
Instance Method Summary collapse
-
#coerce_array(value, options = {}) ⇒ Array
Coerce the value into an Array.
-
#coerce_boolean(value, options = {}) ⇒ Boolean
Corce the value into true or false.
-
#coerce_date(value, options = {}) ⇒ Date?
Coerce the value into a Date.
-
#coerce_float(value, options = {}) ⇒ Float?
Coerce the value into a Float.
-
#coerce_hash(value, options = {}) ⇒ Hash
Coerce the value into a Hash.
-
#coerce_integer(value, options = {}) ⇒ Integer?
Coerce the value into an Integer.
-
#coerce_string(value, options = {}) ⇒ String?
Coerce the value into a String or nil if no value given.
Instance Method Details
#coerce_array(value, options = {}) ⇒ Array
Coerce the value into an Array.
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/organ/coercer.rb', line 51 def coerce_array(value, = {}) element_type = [:element_type] value = value.values if value.kind_of?(Hash) if value.kind_of?(Array) if element_type value.map do |array_element| send("coerce_#{element_type}", array_element) end else value end else [] end end |
#coerce_boolean(value, options = {}) ⇒ Boolean
Corce the value into true or false.
34 35 36 37 |
# File 'lib/organ/coercer.rb', line 34 def coerce_boolean(value, = {}) value = value =~ [:pattern] if .has_key?(:pattern) !!value end |
#coerce_date(value, options = {}) ⇒ Date?
Coerce the value into a Date.
135 136 137 138 139 140 141 142 |
# File 'lib/organ/coercer.rb', line 135 def coerce_date(value, = {}) value = coerce_string(value) begin Date.strptime(value, .fetch(:format, "%Y-%m-%d")) rescue ArgumentError nil end end |
#coerce_float(value, options = {}) ⇒ Float?
Coerce the value into a Float.
74 75 76 |
# File 'lib/organ/coercer.rb', line 74 def coerce_float(value, = {}) Float(value) rescue nil end |
#coerce_hash(value, options = {}) ⇒ Hash
Coerce the value into a Hash.
91 92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/organ/coercer.rb', line 91 def coerce_hash(value, = {}) key_type = [:key_type] value_type = [:value_type] if value.kind_of?(Hash) value.each_with_object({}) do |(key, value), coerced_hash| key = send("coerce_#{key_type}", key) if key_type value = send("coerce_#{value_type}", value) if value_type coerced_hash[key] = value end else {} end end |
#coerce_integer(value, options = {}) ⇒ Integer?
Coerce the value into an Integer.
114 115 116 117 118 119 120 121 |
# File 'lib/organ/coercer.rb', line 114 def coerce_integer(value, = {}) value = value.to_s if value.match(/\A0|[1-9]\d*\z/) value.to_i else nil end end |
#coerce_string(value, options = {}) ⇒ String?
Coerce the value into a String or nil if no value given.
16 17 18 19 20 21 22 |
# File 'lib/organ/coercer.rb', line 16 def coerce_string(value, = {}) value = value ? value.to_s : nil if value && [:trim] value = value.strip.gsub(/\s{2,}/, " ") end value end |