Class: ENVied::Coercer::ENViedString

Inherits:
Object
  • Object
show all
Defined in:
lib/envied/coercer/envied_string.rb

Constant Summary collapse

TRUE_VALUES =
%w[1 on t true y yes].freeze
FALSE_VALUES =
%w[0 off f false n no].freeze
BOOLEAN_MAP =
(TRUE_VALUES.product([ true ]) + FALSE_VALUES.product([ false ])).to_h.freeze

Instance Method Summary collapse

Instance Method Details

#to_array(str) ⇒ Object



6
7
8
# File 'lib/envied/coercer/envied_string.rb', line 6

def to_array(str)
  str.split(/(?<!\\),/).map{|i| i.gsub(/\\,/,',') }
end

#to_boolean(str) ⇒ Object



10
11
12
13
14
# File 'lib/envied/coercer/envied_string.rb', line 10

def to_boolean(str)
  BOOLEAN_MAP.fetch(str&.downcase) do
    raise_unsupported_coercion(str, __method__)
  end
end

#to_date(str) ⇒ Object



16
17
18
19
20
21
# File 'lib/envied/coercer/envied_string.rb', line 16

def to_date(str)
  require 'date'
  ::Date.parse(str)
rescue ArgumentError
  raise_unsupported_coercion(str, __method__)
end

#to_float(str) ⇒ Object



23
24
25
26
27
# File 'lib/envied/coercer/envied_string.rb', line 23

def to_float(str)
  Float(str)
rescue ArgumentError
  raise_unsupported_coercion(str, __method__)
end

#to_hash(str) ⇒ Object



29
30
31
32
# File 'lib/envied/coercer/envied_string.rb', line 29

def to_hash(str)
  require 'cgi'
  ::CGI.parse(str).map { |key, values| [key, values[0]] }.to_h
end

#to_integer(str) ⇒ Object



58
59
60
61
62
# File 'lib/envied/coercer/envied_string.rb', line 58

def to_integer(str)
  Integer(str)
rescue ArgumentError
  raise_unsupported_coercion(str, __method__)
end

#to_string(str) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/envied/coercer/envied_string.rb', line 34

def to_string(str)
  if str.respond_to?(:to_str)
    str.public_send(:to_str)
  else
    raise_unsupported_coercion(str, __method__)
  end
end

#to_symbol(str) ⇒ Object



42
43
44
# File 'lib/envied/coercer/envied_string.rb', line 42

def to_symbol(str)
  str.to_sym
end

#to_time(str) ⇒ Object



46
47
48
49
50
51
# File 'lib/envied/coercer/envied_string.rb', line 46

def to_time(str)
  require 'time'
  ::Time.parse(str)
rescue ArgumentError
  raise_unsupported_coercion(str, __method__)
end

#to_uri(str) ⇒ Object



53
54
55
56
# File 'lib/envied/coercer/envied_string.rb', line 53

def to_uri(str)
  require 'uri'
  ::URI.parse(str)
end