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.
71 72 73 74 75 76 77 78 79 |
# File 'lib/super_settings/coerce.rb', line 71 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 |
# File 'lib/super_settings/coerce.rb', line 23 def boolean(value) return false if value == false return nil if blank?(value) !FALSE_VALUES.include?(value.to_s.downcase) end |
.present?(value) ⇒ Boolean
Returns true if the value is not nil and not empty.
82 83 84 |
# File 'lib/super_settings/coerce.rb', line 82 def present?(value) !blank?(value) end |
.string(value) ⇒ String
Cast a value to a string.
55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/super_settings/coerce.rb', line 55 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.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/super_settings/coerce.rb', line 34 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 |