Class: Versionomy::Conversion::Parsing

Inherits:
Base
  • Object
show all
Defined in:
lib/versionomy/conversion/parsing.rb

Overview

A conversion strategy that relies on parsing. Essentially, it unparses the value and then attempts to parse it with the new format.

Defined Under Namespace

Classes: Builder

Instance Method Summary collapse

Methods inherited from Base

#inspect, #to_s

Constructor Details

#initialize(&block_) ⇒ Parsing

Create a parsing conversion.

By default, this just unparses and reparses using the default parse settings. In some cases, this may be enough, but you may wish to improve the reliability of the conversion by tweaking the parsing settings. To do so, pass a block to the new method, and call methods of Versionomy::Conversion::Parsing::Builder in that block.


58
59
60
61
62
63
64
65
66
67
# File 'lib/versionomy/conversion/parsing.rb', line 58

def initialize(&block_)
  if block_
    builder_ = Builder.new
    ::Blockenspiel.invoke(block_, builder_)
    @original_value_modifier = builder_._get_original_value_modifier
    @string_modifier = builder_._get_string_modifier
    @unparse_params_modifier = builder_._get_unparse_params_modifier
    @parse_params_generator ||= builder_._get_parse_params_generator
  end
end

Instance Method Details

#convert_value(value_, format_, convert_params_ = nil) ⇒ Object

Returns a value equivalent to the given value in the given format.

The convert_params are passed to this conversion's customization blocks (if any).

Raises Versionomy::Errors::ConversionError if the conversion failed. Typically, this is due to a failure of the parsing or unparsing.


78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/versionomy/conversion/parsing.rb', line 78

def convert_value(value_, format_, convert_params_=nil)
  begin
    convert_params_ ||= {}
    if @original_value_modifier
      value_ = @original_value_modifier.call(value_, convert_params_)
    end
    unparse_params_ = value_.unparse_params || {}
    if @unparse_params_modifier
      unparse_params_ = @unparse_params_modifier.call(unparse_params_, convert_params_)
    end
    string_ = value_.unparse(unparse_params_)
    if @string_modifier
      string_ = @string_modifier.call(string_, convert_params_)
    end
    if @parse_params_generator
      parse_params_ = @parse_params_generator.call(convert_params_)
    else
      parse_params_ = nil
    end
    new_value_ = format_.parse(string_, parse_params_)
    return new_value_
  rescue Errors::UnparseError => ex_
    raise Errors::ConversionError, "Unparsing failed: #{ex_.inspect}"
  rescue Errors::ParseError => ex_
    raise Errors::ConversionError, "Parsing failed: #{ex_.inspect}"
  end
end