Class: Lookbook::StringValueCaster

Inherits:
Service
  • Object
show all
Defined in:
lib/lookbook/services/string_value_caster.rb

Instance Method Summary collapse

Methods inherited from Service

call

Constructor Details

#initialize(value, type = "string") ⇒ StringValueCaster

Returns a new instance of StringValueCaster.



5
6
7
8
9
10
11
12
13
# File 'lib/lookbook/services/string_value_caster.rb', line 5

def initialize(value, type = "string")
  @value = value.to_s
  @type = type.to_s.downcase
  @cast_method = :"cast_to_#{@type}"

  unless respond_to?(@cast_method)
    raise ArgumentError.new "'#{@type}' is not a valid value type to cast to."
  end
end

Instance Method Details

#active_model_castObject Also known as: cast_to_boolean, cast_to_integer, cast_to_float



51
52
53
54
# File 'lib/lookbook/services/string_value_caster.rb', line 51

def active_model_cast
  type_class = "ActiveModel::Type::#{@type.camelize}".constantize
  type_class.new.cast(@value)
end

#callObject



15
16
17
18
19
20
21
# File 'lib/lookbook/services/string_value_caster.rb', line 15

def call
  return @nil if @value.empty?
  public_send(@cast_method)
rescue => exception
  Lookbook.logger.debug "Failed to parse '#{@value}' into a '#{@type}' [#{exception}]"
  raise exception
end

#cast_to_arrayObject



39
40
41
42
43
44
45
# File 'lib/lookbook/services/string_value_caster.rb', line 39

def cast_to_array
  result = YamlParser.call(@value)
  unless result.is_a?(Array)
    raise ParserError.new "'#{@value}' is not a YAML Array"
  end
  result
end

#cast_to_datetimeObject



47
48
49
# File 'lib/lookbook/services/string_value_caster.rb', line 47

def cast_to_datetime
  DateTime.parse(@value)
end

#cast_to_hashObject



31
32
33
34
35
36
37
# File 'lib/lookbook/services/string_value_caster.rb', line 31

def cast_to_hash
  result = YamlParser.call(@value)
  unless result.is_a?(Hash)
    raise ParserError.new "'#{@value}' is not a YAML Hash"
  end
  result
end

#cast_to_stringObject



23
24
25
# File 'lib/lookbook/services/string_value_caster.rb', line 23

def cast_to_string
  @value
end

#cast_to_symbolObject



27
28
29
# File 'lib/lookbook/services/string_value_caster.rb', line 27

def cast_to_symbol
  @value.delete_prefix(":").to_sym if @value.present?
end