Class: Kamaze::Project::Tools::Vagrant::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/kamaze/project/tools/vagrant/writer.rb,
lib/kamaze/project/tools/vagrant/writer.rb

Overview

Responsible to write a Vagrantfile

Vagrantfile is written as a standalone, i. e. boxes variable is set as a base64 string. Vagrantfile defines the necessary methods to setup VMs from boxes.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template, output_file = 'Vagrantfile') ⇒ Writer

Returns a new instance of Writer.

Parameters:

  • template (String)
  • output_file (String) (defaults to: 'Vagrantfile')


36
37
38
39
40
41
42
# File 'lib/kamaze/project/tools/vagrant/writer.rb', line 36

def initialize(template, output_file = 'Vagrantfile')
  template = ::Pathname.new(template)

  @template = template
  @template = template.join('Vagrantfile') if template.directory?
  @output_file = output_file
end

Instance Attribute Details

#output_filePathname (readonly)

Path to Vagrantfile

Returns:

  • (Pathname)


32
33
34
# File 'lib/kamaze/project/tools/vagrant/writer.rb', line 32

def output_file
  @output_file
end

#template::Pathname (readonly)

Template used to generate Vagrantfile

Returns:

  • (::Pathname)


27
28
29
# File 'lib/kamaze/project/tools/vagrant/writer.rb', line 27

def template
  @template
end

Instance Method Details

#templatize(yaml) ⇒ String (protected)

Make content (used to write Vagrantfile)

Parameters:

  • yaml (String)

Returns:

  • (String)


59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/kamaze/project/tools/vagrant/writer.rb', line 59

def templatize(yaml)
  boxes64 = Base64.strict_encode64(yaml).yield_self do |text|
    word_wrap(text, 70).map { |s| "\s\s'#{s}'\\" }.join("\n").chomp('\\')
  end

  ['# frozen_string_literal: true',
   '# vim: ai ts=2 sts=2 et sw=2 ft=ruby', nil,
   '[:base64, :yaml, :pp].each { |req| require req.to_s }', nil,
   "cnf64 = \\\n#{boxes64}", nil,
   'boxes = YAML.safe_load(Base64.strict_decode64(cnf64), [Symbol])', nil,
   template.read.gsub(/^#.*\n/, '')]
    .map(&:to_s).join("\n").gsub(/\n\n+/, "\n\n")
end

#word_wrap(text, width = 80) ⇒ Array<String> (protected)

Wrap text into small chunks

Parameters:

  • text (String)
  • width (Fixnum) (defaults to: 80)

Returns:

  • (Array<String>)


78
79
80
# File 'lib/kamaze/project/tools/vagrant/writer.rb', line 78

def word_wrap(text, width = 80)
  text.each_char.each_slice(width).to_a.map(&:join)
end

#write(boxes) ⇒ Object

Write Vagrantfile based on given boxes

Parameters:

  • boxes (Hash)


47
48
49
50
51
# File 'lib/kamaze/project/tools/vagrant/writer.rb', line 47

def write(boxes)
  ::YAML.dump(boxes)
        .yield_self { |yaml| templatize(yaml) }
        .yield_self { |content| output_file.write(content) }
end