Class: Opal::ERB::Compiler

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

Constant Summary

BLOCK_EXPR =
/\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/

Instance Method Summary collapse

Constructor Details

#initialize(source, file_name = '(erb)') ⇒ Compiler

Returns a new instance of Compiler



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

def initialize(source, file_name = '(erb)')
  @source, @file_name, @result = source, file_name, source
end

Instance Method Details

#compileObject



48
49
50
# File 'opal/lib/opal/erb.rb', line 48

def compile
  Opal.compile prepared_source
end

#find_code(result) ⇒ Object



72
73
74
75
76
# File 'opal/lib/opal/erb.rb', line 72

def find_code(result)
  result.gsub(/<%([\s\S]+?)%>/) do
    "\")\n#{ $1 }\noutput_buffer.append(\""
  end
end

#find_contents(result) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
# File 'opal/lib/opal/erb.rb', line 60

def find_contents(result)
  result.gsub(/<%=([\s\S]+?)%>/) do
    inner = $1.gsub(/\\'/, "'").gsub(/\\"/, '"')

    if inner =~ BLOCK_EXPR
      "\")\noutput_buffer.append= #{ inner }\noutput_buffer.append(\""
    else
      "\")\noutput_buffer.append=(#{ inner })\noutput_buffer.append(\""
    end
  end
end

#fix_quotes(result) ⇒ Object



52
53
54
# File 'opal/lib/opal/erb.rb', line 52

def fix_quotes(result)
  result.gsub '"', '\\"'
end

#prepared_sourceObject



36
37
38
39
40
41
42
43
44
45
46
# File 'opal/lib/opal/erb.rb', line 36

def prepared_source
  @prepared_source ||= begin
    source = @source
    source = fix_quotes(source)
    source = find_contents(source)
    source = find_code(source)
    source = wrap_compiled(source)
    source = require_erb(source)
    source
  end
end

#require_erb(result) ⇒ Object



56
57
58
# File 'opal/lib/opal/erb.rb', line 56

def require_erb(result)
  'require "erb";'+result
end

#wrap_compiled(result) ⇒ Object



78
79
80
81
# File 'opal/lib/opal/erb.rb', line 78

def wrap_compiled(result)
  path = @file_name.sub(/\.opalerb$/, '')
  result = "Template.new('#{path}') do |output_buffer|\noutput_buffer.append(\"#{result}\")\noutput_buffer.join\nend\n"
end