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



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

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

Instance Method Details

#compileObject



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

def compile
  Opal.compile prepared_source
end

#find_code(result) ⇒ Object



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

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

#find_contents(result) ⇒ Object



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

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



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

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

#prepared_sourceObject



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

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



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

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

#wrap_compiled(result) ⇒ Object



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

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