Class: Graml::FlattenYaml
- Inherits:
-
Object
- Object
- Graml::FlattenYaml
- Defined in:
- lib/graml/flatten_yaml.rb
Defined Under Namespace
Classes: Item
Instance Method Summary collapse
- #entries ⇒ Object
- #flatten ⇒ Object
- #flatten_hash(hash, prefix = nil) ⇒ Object
-
#initialize(pathname) ⇒ FlattenYaml
constructor
A new instance of FlattenYaml.
- #truncate(string, max = 50) ⇒ Object
- #with_line_numbers ⇒ Object
Constructor Details
#initialize(pathname) ⇒ FlattenYaml
Returns a new instance of FlattenYaml.
8 9 10 |
# File 'lib/graml/flatten_yaml.rb', line 8 def initialize(pathname) @pathname = pathname end |
Instance Method Details
#entries ⇒ Object
12 13 14 |
# File 'lib/graml/flatten_yaml.rb', line 12 def entries flatten end |
#flatten ⇒ Object
16 17 18 19 20 |
# File 'lib/graml/flatten_yaml.rb', line 16 def flatten with_line_numbers.compact.flat_map do |line| flatten_hash(line) if line.is_a?(Hash) end.compact end |
#flatten_hash(hash, prefix = nil) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/graml/flatten_yaml.rb', line 22 def flatten_hash(hash, prefix = nil) hash.flat_map do |key, value| if value.is_a?(Graml::Data) key = [prefix, key].compact.join(".") Item.new(key: key, value: truncate(value.value.to_s), line: value.line) elsif value.is_a?(Hash) flatten_hash(value, [prefix, key].compact.join(".")) end end rescue StandardError => e warn "Error parsing #{@pathname}, #{e.}" end |
#truncate(string, max = 50) ⇒ Object
50 51 52 |
# File 'lib/graml/flatten_yaml.rb', line 50 def truncate(string, max = 50) string.length > max ? "#{string[0...max]}..." : string end |
#with_line_numbers ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/graml/flatten_yaml.rb', line 35 def with_line_numbers parser = Psych::Parser.new(LineNumberHandler.new) parser.handler.parser = parser parser.parse(File.read(@pathname)) parser.handler.root.to_ruby rescue Psych::SyntaxError warn "Invalid YAML #{@pathname}" [] rescue StandardError => e warn "Error parsing #{@pathname}, #{e.}" [] end |