Class: Flatito::FlattenYaml
- Inherits:
-
Object
- Object
- Flatito::FlattenYaml
- Defined in:
- lib/flatito/flatten_yaml.rb
Defined Under Namespace
Classes: Item
Instance Method Summary collapse
- #flatten_hash(hash, prefix = nil) ⇒ Object
-
#initialize(pathname) ⇒ FlattenYaml
constructor
A new instance of FlattenYaml.
- #items ⇒ Object
- #truncate(string, max = 50) ⇒ Object
- #with_line_numbers ⇒ Object
Constructor Details
#initialize(pathname) ⇒ FlattenYaml
Returns a new instance of FlattenYaml.
6 7 8 |
# File 'lib/flatito/flatten_yaml.rb', line 6 def initialize(pathname) @pathname = pathname end |
Instance Method Details
#flatten_hash(hash, prefix = nil) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/flatito/flatten_yaml.rb', line 16 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 rescue StandardError => e warn "Error parsing #{@pathname}, #{e.message}" end |
#items ⇒ Object
10 11 12 13 14 |
# File 'lib/flatito/flatten_yaml.rb', line 10 def items with_line_numbers.compact.flat_map do |line| flatten_hash(line) if line.is_a?(Hash) end.compact end |
#truncate(string, max = 50) ⇒ Object
46 47 48 |
# File 'lib/flatito/flatten_yaml.rb', line 46 def truncate(string, max = 50) string.length > max ? "#{string[0...max]}..." : string end |
#with_line_numbers ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/flatito/flatten_yaml.rb', line 30 def with_line_numbers handler = YAMLWithLineNumber::TreeBuilder.new handler.parser = Psych::Parser.new(handler) handler.parser.parse(File.read(@pathname)) YAMLWithLineNumber::VisitorsToRuby.create.accept(handler.root) rescue Psych::SyntaxError warn "Invalid YAML #{@pathname}" [] rescue StandardError => e warn "Error parsing #{@pathname}, #{e.message}" [] end |