Class: CMDB::FileRewriter

Inherits:
Object
  • Object
show all
Defined in:
lib/cmdb/rewriter.rb

Overview

Tool that rewrites the contents of a single YAML, JSON or similar data file. The rewriting is done in-memory and isn’t saved back to disk until someone calls #save, allowing the caller to check #missing_keys before making a decision whether to proceed.

Constant Summary collapse

REPLACEMENT_TOKEN =

Regexp that matches a well-formed replacement token in YML or JSON

/^<<(.*)>>$/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, encoder) ⇒ FileRewriter

Load YAML, JSON or similar into memory as a Ruby object graph.



86
87
88
89
90
# File 'lib/cmdb/rewriter.rb', line 86

def initialize(file, encoder)
  @file = file
  @encoder = encoder
  @data = @encoder.load(File.read(file))
end

Instance Attribute Details

#missing_keysObject (readonly)

Returns the value of attribute missing_keys.



83
84
85
# File 'lib/cmdb/rewriter.rb', line 83

def missing_keys
  @missing_keys
end

Instance Method Details

#rewrite(cmdb) ⇒ Integer

Peform CMDB input replacement on in-memory objects. Validate that the result can be saved.

Raises:

  • (Errno::EACCES)


95
96
97
98
99
100
101
102
103
104
105
# File 'lib/cmdb/rewriter.rb', line 95

def rewrite(cmdb)
  @total = 0
  @missing_keys = []
  @data = visit(cmdb, @data)

  # Very important; DO NOT REMOVE. This is how we validate that #save will work.
  @encoder.dump(@data)
  raise Errno::EACCES.new(@file) unless File.writable?(@file)

  @total
end

#saveObject



107
108
109
# File 'lib/cmdb/rewriter.rb', line 107

def save
  File.open(@file, 'w') { |f| f.write @encoder.dump(@data) }
end