Class: Opal::Builder

Inherits:
Object show all
Defined in:
opal/lib/opal/builder.rb

Defined Under Namespace

Modules: Util

Constant Summary

BUILDERS =
{ ".rb" => :build_ruby, ".js" => :build_js, ".erb" => :build_erb }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Builder

Returns a new instance of Builder



13
14
15
16
17
# File 'opal/lib/opal/builder.rb', line 13

def initialize(options = {})
  @paths = options.delete(:paths) || Opal.paths.clone
  @options = options
  @handled = {}
end

Class Method Details

.build(name) ⇒ Object



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

def self.build(name)
  Builder.new.build name
end

Instance Method Details

#append_path(path) ⇒ Object



19
20
21
# File 'opal/lib/opal/builder.rb', line 19

def append_path(path)
  @paths << path
end

#build(path) ⇒ Object



23
24
25
26
27
28
29
# File 'opal/lib/opal/builder.rb', line 23

def build(path)
  @segments = []

  require_asset path

  @segments.join
end

#build_asset(path) ⇒ Object



63
64
65
66
67
68
69
70
71
# File 'opal/lib/opal/builder.rb', line 63

def build_asset(path)
  ext = File.extname path

  unless builder = BUILDERS[ext]
    raise "Unknown builder for #{ext}"
  end

  @segments << __send__(builder, path)
end

#build_erb(path) ⇒ Object



94
95
96
# File 'opal/lib/opal/builder.rb', line 94

def build_erb(path)
  ::ERB.new(File.read(path)).result binding
end

#build_js(path) ⇒ Object



90
91
92
# File 'opal/lib/opal/builder.rb', line 90

def build_js(path)
  File.read(path)
end

#build_ruby(path) ⇒ Object



86
87
88
# File 'opal/lib/opal/builder.rb', line 86

def build_ruby(path)
  compile_ruby File.read(path), @options.clone
end

#build_str(str, options = {}) ⇒ Object



31
32
33
34
35
# File 'opal/lib/opal/builder.rb', line 31

def build_str(str, options = {})
  @segments = []
  @segments << compile_ruby(str, options)
  @segments.join
end

#compile_ruby(str, options = nil) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
# File 'opal/lib/opal/builder.rb', line 73

def compile_ruby(str, options = nil)
  options ||= @options.clone

  compiler = Compiler.new
  result = compiler.compile str, options

  compiler.requires.each do |r|
    require_asset r
  end

  result
end

#find_asset(path) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'opal/lib/opal/builder.rb', line 46

def find_asset(path)
  path.untaint if path =~ /\A(\w[-.\w]*\/?)+\Z/
  file_types = %w[.rb .js .js.erb]

  @paths.each do |root|
    file_types.each do |type|
      test = File.join root, "#{path}#{type}"

      if File.exist? test
        return test
      end
    end
  end

  raise "Could not find asset: #{path}"
end

#require_asset(path) ⇒ Object



37
38
39
40
41
42
43
44
# File 'opal/lib/opal/builder.rb', line 37

def require_asset(path)
  location = find_asset path

  unless @handled[location]
    @handled[location] = true
    build_asset location
  end
end