Class: Opal::ERB::Compiler

Inherits:
Object
  • 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



34
35
36
# File 'opal/lib/opal/erb.rb', line 34

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

Instance Method Details

#compileObject



50
51
52
# File 'opal/lib/opal/erb.rb', line 50

def compile
  Opal.compile prepared_source
end

#find_code(result) ⇒ Object



74
75
76
77
78
79
# File 'opal/lib/opal/erb.rb', line 74

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

#find_contents(result) ⇒ Object



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

def find_contents(result)
  result.gsub(/<%=([\s\S]+?)%>/) do
    inner = Regexp.last_match(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



54
55
56
# File 'opal/lib/opal/erb.rb', line 54

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

#prepared_sourceObject



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

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



58
59
60
# File 'opal/lib/opal/erb.rb', line 58

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

#wrap_compiled(result) ⇒ Object



81
82
83
84
# File 'opal/lib/opal/erb.rb', line 81

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