class Tolq::Parsers::Yaml::Parser

Public Class Methods

new(quality:, source_language_code:, target_language_code:) click to toggle source

Creates a new Yaml parser

@param quality [Symbol] the Tolq quality to order in @param source_language_code [String] The two letter source language code @param target_language_code [String] The two letter target language code @return [Tolq::Parsers::Yaml::Parser

# File lib/yaml/parser.rb, line 10
def initialize(quality:, source_language_code:, target_language_code:)
  @quality = quality
  @source_language_code = source_language_code
  @target_language_code = target_language_code
end

Public Instance Methods

parse(yaml_text) click to toggle source

Parses a YAML text

@param yaml_text [String] the yaml format text to parse @return [Hash] A hash suitable to be converted to json for a Tolq api request

# File lib/yaml/parser.rb, line 20
def parse(yaml_text)
  request_data = extract_request_data_from_yaml(yaml_text)

  {
    "request" => request_data,
    "source_language_code" => @source_language_code,
    "target_language_code" => @target_language_code,
    "quality" => @quality.to_s
  }
end

Private Instance Methods

extract_request_data_from_yaml(yaml_text) click to toggle source
# File lib/yaml/parser.rb, line 33
def extract_request_data_from_yaml(yaml_text)
  parsed = YAML.load(yaml_text)
  hash = recursively_extract(strip_root(parsed))
  hash.inject({}) do |acc, (k,v)|
    acc[k] = { 'text' => v} if v.length > 0
    acc
  end
end
recursively_extract(val, mem={}, prefix="") click to toggle source
# File lib/yaml/parser.rb, line 42
def recursively_extract(val, mem={}, prefix="")
  return mem.update(prefix => val) unless val.is_a?(Hash)
  val.each do |k,v|
    prefix = prefix.length > 0 && prefix !~ /\.$/ ? prefix + "." : prefix
    recursively_extract(v, mem, prefix + k.to_s)
  end
  mem
end
strip_root(hash) click to toggle source
# File lib/yaml/parser.rb, line 51
def strip_root(hash)
  first_key = hash.keys.first
  if first_key.to_s.length == 2 && hash[first_key].is_a?(Hash)
    hash[first_key]
  else
    hash
  end
end