Class: Vagrant::Util::StringBlockEditor

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/util/string_block_editor.rb

Overview

This class modifies strings by creating and managing Vagrant-owned “blocks” via wrapping them in specially formed comments.

This is useful when modifying a file that someone else owns and adding automatic entries into it. Example: /etc/exports or some other configuration file.

Vagrant marks ownership of a block in the string by wrapping it in VAGRANT-BEGIN and VAGRANT-END comments with a unique ID. Example:

foo
# VAGRANT-BEGIN: id
some contents
created by vagrant
# VAGRANT-END: id

The goal of this class is to be able to insert and remove these blocks without modifying anything else in the string.

The strings usually come from files but it is up to the caller to manage the file resource.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ StringBlockEditor

Returns a new instance of StringBlockEditor.



31
32
33
# File 'lib/vagrant/util/string_block_editor.rb', line 31

def initialize(string)
  @value = string
end

Instance Attribute Details

#valueString (readonly)

The current string value. This is the value that is modified by the methods below.

Returns:

  • (String)


29
30
31
# File 'lib/vagrant/util/string_block_editor.rb', line 29

def value
  @value
end

Instance Method Details

#delete(key) ⇒ Object

This deletes the block with the given key if it exists.



46
47
48
49
50
# File 'lib/vagrant/util/string_block_editor.rb', line 46

def delete(key)
  key    = Regexp.quote(key)
  regexp = /^#\s*VAGRANT-BEGIN:\s*#{key}$.*^#\s*VAGRANT-END:\s*#{key}$\r?\n?/m
  @value.gsub!(regexp, "")
end

#get(key) ⇒ Object

This gets the value of the block with the given key.



53
54
55
56
57
58
59
# File 'lib/vagrant/util/string_block_editor.rb', line 53

def get(key)
  key    = Regexp.quote(key)
  regexp = /^#\s*VAGRANT-BEGIN:\s*#{key}$\r?\n?(.*?)\r?\n?^#\s*VAGRANT-END:\s*#{key}$\r?\n?/m
  match  = regexp.match(@value)
  return nil if !match
  match[1]
end

#insert(key, value) ⇒ Object

This inserts a block with the given key and value.

Parameters:

  • key (String)
  • value (String)


65
66
67
68
69
70
71
72
73
74
# File 'lib/vagrant/util/string_block_editor.rb', line 65

def insert(key, value)
  # Insert the new block into the value
  new_block = <<BLOCK
# VAGRANT-BEGIN: #{key}
#{value.strip}
# VAGRANT-END: #{key}
BLOCK

  @value << new_block
end

#keys<Array<String>]

This returns the keys (or ids) that are in the string.

Returns:

  • (<Array<String>])

    <Array<String>]



38
39
40
41
42
43
# File 'lib/vagrant/util/string_block_editor.rb', line 38

def keys
  regexp = /^#\s*VAGRANT-BEGIN:\s*(.+?)$\r?\n?(.*)$\r?\n?^#\s*VAGRANT-END:\s(\1)$/m
  @value.scan(regexp).map do |match|
    match[0]
  end
end