class Versionomy::Conversion::Parsing

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

Public Class Methods

new(&block_) click to toggle source

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.

# 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

Public Instance Methods

convert_value(value_, format_, convert_params_=nil) click to toggle source

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.

# 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