Class: Basis::Template

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(srcdir) ⇒ Template

Returns a new instance of Template.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/basis/template.rb', line 9

def initialize srcdir
  @srcdir = File.expand_path srcdir

  Dir.chdir @srcdir do
    remote  = `git remote -v`.split(/\s/)[1]
    rev     = `git rev-parse HEAD`
    @origin = "#{remote}@#{rev}"
  end

  if File.exist?(template = "#@srcdir/.basis/template.rb")
    src = IO.read template
    extend eval("Module.new do;#{src};end", nil, template, 1)
  end
end

Instance Attribute Details

#originObject (readonly)

Returns the value of attribute origin.



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

def origin
  @origin
end

#srcdirObject (readonly)

Returns the value of attribute srcdir.



6
7
8
# File 'lib/basis/template.rb', line 6

def srcdir
  @srcdir
end

Instance Method Details

#descriptionObject



24
25
26
# File 'lib/basis/template.rb', line 24

def description
  "An awesome template."
end

#render(destdir, context) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/basis/template.rb', line 28

def render destdir, context
  FileUtils.mkdir_p File.join(destdir, ".basis")

  File.open File.join(destdir, ".basis", "origin"), "wb" do |f|
    f.puts origin
  end

  Dir.glob("#{srcdir}/**/*", File::FNM_DOTMATCH).each do |src|
    next unless File.file? src

    rel = src.gsub(/^#{srcdir}\//, "")
    next if /^\.basis/ =~ rel || /^\.git\// =~ rel

    target = "#{destdir}/#{rel}"

    target.gsub!(/\[([a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)*)\]/i) do |expr|
      context[$1] || expr
    end

    FileUtils.mkdir_p File.dirname(target)

    # FIX: prompt for overwrite?

    contents = File.read src

    if contents =~ /\[%.*%\]/
      File.open target, "wb" do |f|
        erb = Erubis::Eruby.new contents,
        :filename => rel, :pattern => '\[% %\]'

        f.write erb.evaluate(context)
      end
    else
      FileUtils.copy src, target
    end

    # FIX: file perms
  end
end