Class: Flatito::FlattenYaml

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/flatito/flatten_yaml.rb

Defined Under Namespace

Classes: Item

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils

#truncate

Constructor Details

#initialize(content, pathname: nil) ⇒ FlattenYaml

Returns a new instance of FlattenYaml.



22
23
24
25
# File 'lib/flatito/flatten_yaml.rb', line 22

def initialize(content, pathname: nil)
  @content = content
  @pathname = pathname
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



20
21
22
# File 'lib/flatito/flatten_yaml.rb', line 20

def content
  @content
end

#pathnameObject (readonly)

Returns the value of attribute pathname.



20
21
22
# File 'lib/flatito/flatten_yaml.rb', line 20

def pathname
  @pathname
end

Class Method Details

.items_from_content(content) ⇒ Object



15
16
17
# File 'lib/flatito/flatten_yaml.rb', line 15

def items_from_content(content)
  new(content).items
end

.items_from_path(pathname) ⇒ Object



10
11
12
13
# File 'lib/flatito/flatten_yaml.rb', line 10

def items_from_path(pathname)
  content = File.read(pathname)
  new(content, pathname: pathname).items
end

Instance Method Details

#flatten_hash(hash, prefix = nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/flatito/flatten_yaml.rb', line 33

def flatten_hash(hash, prefix = nil)
  hash.flat_map do |key, value|
    if value.is_a?(YAMLWithLineNumber::ValueWithLineNumbers)
      if value.value.is_a?(Hash)
        flatten_hash(value.value, [prefix, key].compact.join("."))
      else
        Item.new(key: [prefix, key].compact.join("."), value: truncate(value.value.to_s), line: value.line)
      end
    end
  end
end

#itemsObject



27
28
29
30
31
# File 'lib/flatito/flatten_yaml.rb', line 27

def items
  with_line_numbers.compact.flat_map do |line|
    flatten_hash(line) if line.is_a?(Hash)
  end.compact
end

#with_line_numbersObject



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/flatito/flatten_yaml.rb', line 45

def with_line_numbers
  handler = YAMLWithLineNumber::TreeBuilder.new
  handler.parser = Psych::Parser.new(handler)

  handler.parser.parse(content)
  YAMLWithLineNumber::VisitorsToRuby.create.accept(handler.root)
rescue Psych::SyntaxError
  warn "Invalid format #{pathname}"
  []
rescue StandardError
  warn "Error parsing #{pathname}"
  []
end