module YamlNormalizer::Helpers::Normalize

This helper holds shared functionality to normalize a YAML string.

Public Instance Methods

normalize_yaml(yaml) click to toggle source

Transforms a given YAML string to a normalized format. @example

class YamlWriter
  include YamlNormalizer::Helpers::Normalize

  def initialize(yaml)
    @yaml = normalize_yaml(yaml)
  end

  def write(file)
    File.open(file,'w') { |f| f.write(@yaml) }
  end
end

@param [String] valid YAML string @return [String] normalized YAML string

# File lib/yaml_normalizer/helpers/normalize.rb, line 24
def normalize_yaml(yaml)
  hashes = parse(yaml).transform
  hashes.each { |hash| hash.extend(Ext::SortByKey) }
  hashes.map(&:sort_by_key).map(&:to_yaml).join
end

Private Instance Methods

parse(yaml) click to toggle source
# File lib/yaml_normalizer/helpers/normalize.rb, line 32
def parse(yaml)
  Psych.parse_stream(yaml)
end
read(file) click to toggle source
# File lib/yaml_normalizer/helpers/normalize.rb, line 36
def read(file)
  File.read(file, mode: 'r:bom|utf-8')
end
relative_path_for(file) click to toggle source
# File lib/yaml_normalizer/helpers/normalize.rb, line 40
def relative_path_for(file)
  realpath = Pathname.new(file).realpath
  realpath.relative_path_from(Pathname.new(Dir.pwd))
end