Class: SuperSettings::Coerce
- Inherits:
-
Object
- Object
- SuperSettings::Coerce
- Defined in:
- lib/super_settings/coerce.rb
Overview
Utility functions for coercing values to other data types.
Constant Summary collapse
- FALSE_VALUES =
Set of values that should be considered false when converting to boolean. rubocop:disable Lint/BooleanSymbol
Set.new([ "0", :"0", "f", :f, "false", :false, "off", :off ]).freeze
Class Method Summary collapse
-
.blank?(value) ⇒ Boolean
True if the value is nil or empty.
-
.boolean(value) ⇒ Boolean
Cast variations of booleans (i.e. “true”, “false”, 1, 0, etc.) to actual boolean objects.
-
.present?(value) ⇒ Boolean
True if the value is not nil and not empty.
-
.string(value) ⇒ String
Cast a value to a string.
-
.time(value) ⇒ Time
Cast a value to a Time object.
Class Method Details
.blank?(value) ⇒ Boolean
Returns true if the value is nil or empty.
74 75 76 77 78 79 80 81 82 |
# File 'lib/super_settings/coerce.rb', line 74 def blank?(value) return true if value.nil? if value.respond_to?(:empty?) value.empty? else value.to_s.empty? end end |
.boolean(value) ⇒ Boolean
Cast variations of booleans (i.e. “true”, “false”, 1, 0, etc.) to actual boolean objects.
23 24 25 26 27 28 29 30 31 |
# File 'lib/super_settings/coerce.rb', line 23 def boolean(value) if value == false false elsif blank?(value) nil else !FALSE_VALUES.include?(value.to_s.downcase) end end |
.present?(value) ⇒ Boolean
Returns true if the value is not nil and not empty.
85 86 87 |
# File 'lib/super_settings/coerce.rb', line 85 def present?(value) !blank?(value) end |
.string(value) ⇒ String
Cast a value to a string.
58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/super_settings/coerce.rb', line 58 def string(value) value = nil if blank?(value) return nil if value.nil? if value.is_a?(String) value elsif value.is_a?(Array) value.join("\n") elsif value.respond_to?(:iso8601) value.iso8601 else value.to_s end end |
.time(value) ⇒ Time
Cast a value to a Time object.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/super_settings/coerce.rb', line 37 def time(value) value = nil if blank?(value) return nil if value.nil? time = if value.is_a?(Numeric) Time.at(value) elsif value.respond_to?(:to_time) value.to_time else Time.parse(value.to_s) end if time.respond_to?(:in_time_zone) && Time.respond_to?(:zone) time = time.in_time_zone(Time.zone) end time end |