Class: Flatito::FlattenYaml

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

Defined Under Namespace

Classes: Item

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(content, pathname: nil) ⇒ FlattenYaml

Returns a new instance of FlattenYaml.



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

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

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



17
18
19
# File 'lib/flatito/flatten_yaml.rb', line 17

def content
  @content
end

#pathnameObject (readonly)

Returns the value of attribute pathname.



17
18
19
# File 'lib/flatito/flatten_yaml.rb', line 17

def pathname
  @pathname
end

Class Method Details

.items_from_content(content, pathname: nil) ⇒ Object



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

def items_from_content(content, pathname: nil)
  new(content, pathname: pathname).items
end

.items_from_path(pathname) ⇒ Object



7
8
9
10
# File 'lib/flatito/flatten_yaml.rb', line 7

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

Instance Method Details

#flatten_hash(hash, prefix = nil) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/flatito/flatten_yaml.rb', line 42

def flatten_hash(hash, prefix = nil)
  hash.filter_map do |key, value|
    next unless value.is_a?(YAMLWithLineNumber::ValueWithLineNumbers)

    full_key = prefix ? "#{prefix}.#{key}" : key
    if value.value.is_a?(Hash)
      flatten_hash(value.value, full_key)
    else
      Item.new(key: full_key, value: value.value.to_s, line: value.line)
    end
  end
end

#itemsObject



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/flatito/flatten_yaml.rb', line 24

def items
  if json?
    result = JsonScanner.scan(content)
    return result if result
  end

  psych_items
rescue StandardError
  warn "Error parsing #{pathname}" if pathname
  []
end

#json?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/flatito/flatten_yaml.rb', line 55

def json?
  content.lstrip.start_with?("{", "[")
end

#psych_itemsObject



36
37
38
39
40
# File 'lib/flatito/flatten_yaml.rb', line 36

def psych_items
  with_line_numbers.filter_map do |line|
    flatten_hash(line) if line.is_a?(Hash)
  end.flatten
end

#with_line_numbersObject



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/flatito/flatten_yaml.rb', line 59

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