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.



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

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.



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

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.

Returns:

  • (Integer)

    number of variables replaced

Raises:

  • (Errno::EACCES)


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

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



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

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