Class: SinatraGen

Inherits:
Object
  • Object
show all
Defined in:
lib/sinatragen.rb,
lib/sinatragen/version.rb

Constant Summary collapse

VERSION =
'0.0.1'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template_dir, target_path, template_data) ⇒ SinatraGen

Returns a new instance of SinatraGen.



12
13
14
15
16
# File 'lib/sinatragen.rb', line 12

def initialize(template_dir, target_path, template_data)
  @template_dir = template_dir
  @template_data = template_data
  @target_path = target_path
end

Instance Attribute Details

#source_filesObject



24
25
26
27
28
29
30
# File 'lib/sinatragen.rb', line 24

def source_files
  @source_files ||= ->{
    Dir[ File.join(template_dir, '*.*'),
         File.join(template_dir, '**/*.*') ].
    map!{|file| file.gsub(@template_dir, '')}
  }[]
end

#target_pathObject

Returns the value of attribute target_path.



8
9
10
# File 'lib/sinatragen.rb', line 8

def target_path
  @target_path
end

#template_dataObject

Returns the value of attribute template_data.



9
10
11
# File 'lib/sinatragen.rb', line 9

def template_data
  @template_data
end

#template_dirObject

Returns the value of attribute template_dir.



7
8
9
# File 'lib/sinatragen.rb', line 7

def template_dir
  @template_dir
end

Instance Method Details

#copy_file(source, dest) ⇒ Object



44
45
46
# File 'lib/sinatragen.rb', line 44

def copy_file(source, dest)
  FileUtils.cp(File.join(@template_dir, source), dest)
end

#file_data(base_file) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/sinatragen.rb', line 36

def file_data(base_file)
  file = File.basename(base_file)
  path = File.dirname(base_file)
  new_path = File.join(@target_path, path)
  new_file = File.join(new_path, file.gsub('.erb', ''))
  [file, path, new_path, new_file]
end

#runObject



18
19
20
21
22
# File 'lib/sinatragen.rb', line 18

def run
  source_files.each do |source_file|
    transfer_file source_file
  end
end

#template_file(source, dest) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/sinatragen.rb', line 48

def template_file(source, dest)
  File.open(dest, 'w') do |source_file|
    template_file = File.join(@template_dir, source)
    template = File.read(template_file)
    source_file << ERB.new(template).
      result(@template_data.instance_eval { binding })
  end
end

#template_file?(filename) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/sinatragen.rb', line 32

def template_file?(filename)
  not filename[/erb/].nil?
end

#transfer_file(base_file) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/sinatragen.rb', line 57

def transfer_file(base_file)
  file, path, new_path, new_file = file_data(base_file)
  FileUtils.mkdir_p(new_path)
  if template_file?(base_file)
    template_file(base_file, new_file)
  else
    copy_file(base_file, new_file)
  end
end