Class: Opal::Builder

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

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



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

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

Class Method Details

.build(name) ⇒ Object



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

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

Instance Method Details

#append_path(path) ⇒ Object



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

def append_path(path)
  @paths << path
end

#build(path) ⇒ Object



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

def build(path)
  @segments = []

  require_asset path

  @segments.join
end

#build_asset(path) ⇒ Object



66
67
68
69
70
71
72
73
74
# File 'opal/lib/opal/builder.rb', line 66

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



97
98
99
# File 'opal/lib/opal/builder.rb', line 97

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

#build_js(path) ⇒ Object



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

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

#build_ruby(path) ⇒ Object



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

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

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



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

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

#compile_ruby(str, options = nil) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
# File 'opal/lib/opal/builder.rb', line 76

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



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

def find_asset(path)
  return path if Pathname(path).absolute?

  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



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

def require_asset(path)
  location = find_asset path

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