Module: GenerateFromTemplates

Includes:
StepPlugin
Included in:
Target::Deb
Defined in:
lib/gpm/target/generate_from_templates.rb

Constant Summary collapse

REPLACEMENT_REGEXP =
/__(\w+)__/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/gpm/target/generate_from_templates.rb', line 6

def self.included(base)
  def base.add_generation_phase(explanation="Expanding templates...")
    in_phase(:file_creation, explanation) { |source| write_files_to_package_dir(source) }
  end
  base.add_generation_phase
  self.plugin_included(base)
end

Instance Method Details

#file_content(template, source, file) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/gpm/target/generate_from_templates.rb', line 50

def file_content(template, source, file)
  contents = template.result(source.instance_eval{ binding() })
  if file.end_with?(".gz")
    zipped = ""
    gz = ::Zlib::GzipWriter.new(StringIO.new(zipped))
    gz.write contents
    gz.close
    contents = zipped
  end
  contents
end

#file_contents_from_templates(source) ⇒ Object



33
34
35
# File 'lib/gpm/target/generate_from_templates.rb', line 33

def file_contents_from_templates(source)
  Hash[*templates.map {|file,template| [packaged_file_name(file,source),file_content(template, source, file)]}.flatten]
end

#packaged_file_name(file_name, source) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/gpm/target/generate_from_templates.rb', line 42

def packaged_file_name(file_name,source)
  to_replace = file_name.scan(REPLACEMENT_REGEXP).flatten
  to_replace.each do |replace|
    file_name = file_name.gsub("__#{replace}__",source.send(replace.to_sym))
  end
  file_name
end

#template_dirObject



18
19
20
# File 'lib/gpm/target/generate_from_templates.rb', line 18

def template_dir
  File.expand_path("../../../templates/#{type}/", File.dirname(__FILE__))
end

#template_filesObject



22
23
24
# File 'lib/gpm/target/generate_from_templates.rb', line 22

def template_files
  template_paths.map {|tp| tp.gsub(/#{template_dir}\//,"")}
end

#template_pathsObject



14
15
16
# File 'lib/gpm/target/generate_from_templates.rb', line 14

def template_paths
  @template_paths ||= Dir["#{template_dir}/**/*.erb"]
end

#templatesObject



26
27
28
29
30
31
# File 'lib/gpm/target/generate_from_templates.rb', line 26

def templates
  Hash[*template_paths.map {|file| FilePathAndPermissions.new(file.gsub(/#{template_dir}\//,"").gsub(".erb",""),File.new(file).lstat.mode)}.zip(template_paths.map do |template_file|
    tpl = File.read(template_file)
    ::ERB.new(tpl, nil,'%<>-')
  end).flatten]
end

#write_files_to_package_dir(source) ⇒ Object



37
38
39
# File 'lib/gpm/target/generate_from_templates.rb', line 37

def write_files_to_package_dir(source)
  write_file_contents_in_directory file_contents_from_templates(source), '.'
end