Class: Compath::YamlFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/compath/yaml_formatter.rb

Constant Summary collapse

QUOTED_KEY_REGEXP =
/^"(?<key>[^"]+)":(?<value>.*)/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(yaml) ⇒ YamlFormatter

Returns a new instance of YamlFormatter.



5
6
7
# File 'lib/compath/yaml_formatter.rb', line 5

def initialize(yaml)
  @yaml = yaml
end

Instance Attribute Details

#yamlObject

Returns the value of attribute yaml.



3
4
5
# File 'lib/compath/yaml_formatter.rb', line 3

def yaml
  @yaml
end

Instance Method Details

#formatObject



9
10
11
12
13
14
# File 'lib/compath/yaml_formatter.rb', line 9

def format
  formatters.each do |formatter|
    self.yaml = formatter.call(yaml)
  end
  yaml
end

#formattersObject



16
17
18
19
20
21
# File 'lib/compath/yaml_formatter.rb', line 16

def formatters
  @formatters ||= [
    remove_trailing_space_formatter,
    remove_quotes_from_keys_formatter,
  ]
end

#remove_quotes_from_keys_formatterObject



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/compath/yaml_formatter.rb', line 30

def remove_quotes_from_keys_formatter
  lambda do |yaml|
    lines = yaml.lines.map do |line|
      if m = QUOTED_KEY_REGEXP.match(line)
        "#{m[:key]}: #{m[:value]}".rstrip
      else
        line.chomp
      end
    end

    lines.map {|x| "#{x}\n" }.join
  end
end

#remove_trailing_space_formatterObject



23
24
25
26
27
# File 'lib/compath/yaml_formatter.rb', line 23

def remove_trailing_space_formatter
  lambda do |yaml|
    yaml.lines.map(&:rstrip).map {|x| "#{x}\n" }.join
  end
end