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.



34
35
36
# File 'lib/vagrant/util/string_block_editor.rb', line 34

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)


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

def value
  @value
end

Instance Method Details

#delete(key) ⇒ Object

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



49
50
51
52
53
# File 'lib/vagrant/util/string_block_editor.rb', line 49

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.



56
57
58
59
60
61
62
# File 'lib/vagrant/util/string_block_editor.rb', line 56

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)


68
69
70
71
72
73
74
75
76
77
# File 'lib/vagrant/util/string_block_editor.rb', line 68

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>])

    ]



41
42
43
44
45
46
# File 'lib/vagrant/util/string_block_editor.rb', line 41

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