Class: KISSGen::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/kissgen/template.rb

Defined Under Namespace

Classes: SourceFileNotFoundError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(generator, path, copy_path) ⇒ Template

Returns a new instance of Template.



7
8
9
10
11
12
13
# File 'lib/kissgen/template.rb', line 7

def initialize(generator, path, copy_path)
  @generator = generator
  @path = path
  @copy_path = copy_path
  
  source_path_check
end

Instance Attribute Details

#generatorObject (readonly)

Returns the value of attribute generator.



5
6
7
# File 'lib/kissgen/template.rb', line 5

def generator
  @generator
end

#pathObject (readonly)

Returns the value of attribute path.



5
6
7
# File 'lib/kissgen/template.rb', line 5

def path
  @path
end

Instance Method Details

#copy_pathObject



15
16
17
# File 'lib/kissgen/template.rb', line 15

def copy_path
  @copy_path.gsub(/%([^\}]*)%/) {|a| @generator.assigns[$1.to_sym]} # Yehuda OWNZ
end

#createObject

This will create the file with parsed data in the destination directory



57
58
59
60
61
62
# File 'lib/kissgen/template.rb', line 57

def create
  puts copy_path
  FileUtils.mkdir_p(File.dirname(full_copy_path))

  write_or_prompt
end

#deleteObject

Will remove the file if it exists



71
72
73
74
# File 'lib/kissgen/template.rb', line 71

def delete
  raise "Need to create the file first. File: #{@file.inspect}" unless @file
  File.delete(full_copy_path)
end

#full_copy_pathObject



27
28
29
# File 'lib/kissgen/template.rb', line 27

def full_copy_path
  File.join @generator.copy_path, copy_path
end

#full_source_pathObject



23
24
25
# File 'lib/kissgen/template.rb', line 23

def full_source_path
  File.join @generator.path, path
end

#outputObject

Parsed ERB output



32
33
34
35
36
37
38
39
# File 'lib/kissgen/template.rb', line 32

def output
  b = binding
  
  # define local assignment variables
  @generator.assigns.each { |name, value| eval "#{name} = \"#{value}\"", b }
  
  ERB.new(File.read(full_source_path), 0, "%<>").result(b)
end

#source_path_checkObject



19
20
21
# File 'lib/kissgen/template.rb', line 19

def source_path_check
  raise SourceFileNotFoundError, "Template source file could not be found at #{full_source_path}" unless File.exists?(full_source_path)
end

#writeObject



64
65
66
67
68
# File 'lib/kissgen/template.rb', line 64

def write
  @file = File.new full_copy_path, "w"
  @file.print output # Taylor OWNZ
  @file.close
end

#write_or_promptObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/kissgen/template.rb', line 41

def write_or_prompt
  if File.exists?(full_copy_path)
    print "Already exists. Replace? (Yn)"
    @replace = gets.chomp
    if ["Y","y",""].include? @replace
      write
      puts "#{copy_path} replaced."
    else
      puts "#{copy_path} preserved."
    end
  else
    write
  end
end