Class: Helium::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/helium/generator.rb

Overview

The Generator class is used by the command-line tools to create copies of the web app and the JavaScript project template. It copies the contents of one of the template directories into a local directory, expanding any files with .erb extensions as ERB templates.

For example, a file jake.yml.erb will be copied into the target dir as jake.yml after being evaluated using ERB.

If a filename contains variable names enclosed in double-underscores, the resulting copy will have those replaced by the value of the named instance variable. For example, __name__.js will be copied to myproj.js if @name = 'myproj'.

Instance Method Summary collapse

Constructor Details

#initialize(template, dir, options = {}) ⇒ Generator

Generators are initialized using the name of the template (a collection of files in the templates directory, a target directory and an option hash. Keys in the option hash become instance variables accessible to ERB templates.



20
21
22
23
24
25
26
# File 'lib/helium/generator.rb', line 20

def initialize(template, dir, options = {})
  options.each do |key, value|
    instance_variable_set("@#{key}", value)
  end
  @_source    = join(TEMPLATES, template)
  @_directory = expand_path(dir)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object

Provide shorthand access to all File methods.



53
54
55
# File 'lib/helium/generator.rb', line 53

def method_missing(*args, &block)
  File.__send__(*args, &block)
end

Instance Method Details

#camelize(string) ⇒ Object

Returns a camelcased copy of the string, for example:

camelize('my-project')
#=> 'MyProject'


62
63
64
65
# File 'lib/helium/generator.rb', line 62

def camelize(string)
  string.gsub(/^(.)/) { $1.upcase }.
         gsub(/[\s\-\_](.)/) { $1.upcase }
end

#run!Object

Runs the generator, copying all files as required. All ERB/name replacement is handled in this method.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/helium/generator.rb', line 30

def run!
  Find.find(@_source) do |path|
    next unless file?(path)
    content = read(path)
    
    # Replace variable names in file paths
    path = path.sub(@_source, '').gsub(/__(.+?)__/) { instance_variable_get("@#{$1}") }
    target = join(@_directory, path)
    
    # Evaluate using ERB if required
    if extname(path) == ERB_EXT
      content = ERB.new(content).result(binding)
      target  = join(dirname(target), basename(target, ERB_EXT))
    end
    
    # Generate destination file
    FileUtils.mkdir_p(dirname(target))
    open(target, 'w') { |f| f.write(content) }
    puts "create #{ basename(@_directory) }#{ target.sub(@_directory, '') }"
  end
end