Module: TypeScript::Rails::Compiler

Defined in:
lib/typescript/rails/compiler.rb

Class Method Summary collapse

Class Method Details

.compile(ts_path, source, context = nil, *options) ⇒ String

Returns compiled JavaScript source code.

Parameters:

  • ts_path (String)
  • source (String)

    TypeScript source code

  • sprockets (Sprockets::Context)

    context object

Returns:

  • (String)

    compiled JavaScript source code



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/typescript/rails/compiler.rb', line 53

def compile(ts_path, source, context=nil, *options)
  if context
    get_all_reference_paths(File.expand_path(ts_path), source) do |abs_path|
      context.depend_on abs_path
    end
  end
  s = replace_relative_references(ts_path, source)
  begin
    ::TypeScript::Ruby.compile(s, *default_options, *options)
  rescue Exception => e
    raise "TypeScript error in file '#{ts_path}':\n#{e.message}"
  end
end

.default_optionsObject



7
# File 'lib/typescript/rails/compiler.rb', line 7

cattr_accessor :default_options

.get_all_reference_paths(path, source, visited_paths = Set.new, &block) ⇒ Object

Get all references

Parameters:

  • path (String)

    Source .ts path

  • source. (String)

    It might be pre-processed by erb.

Yield Returns:

  • (String)

    matched ref abs_path



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/typescript/rails/compiler.rb', line 34

def get_all_reference_paths(path, source, visited_paths=Set.new, &block)
  visited_paths << path
  source ||= File.read(path)
  source.each_line do |l|
    if l.starts_with?('///') && !(m = %r!^///\s*<reference\s+path=(?:"([^"]+)"|'([^']+)')\s*/>\s*!.match(l)).nil?
      matched_path = m.captures.compact[0]
      abs_matched_path = File.expand_path(matched_path, File.dirname(path))
      unless visited_paths.include? abs_matched_path
        block.call abs_matched_path
        get_all_reference_paths(abs_matched_path, nil, visited_paths, &block)
      end
    end
  end
end

.replace_relative_references(ts_path, source) ⇒ String

Replace relative paths specified in /// <reference path=“…” /> with absolute paths.

Parameters:

  • ts_path (String)

    Source .ts path

  • source. (String)

    It might be pre-processed by erb.

Returns:

  • (String)

    replaces source



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/typescript/rails/compiler.rb', line 14

def replace_relative_references(ts_path, source)
  ts_dir = File.dirname(File.expand_path(ts_path))
  escaped_dir = ts_dir.gsub(/["\\]/, '\\\\\&') # "\"" => "\\\"", '\\' => '\\\\'

  # Why don't we just use gsub? Because it display odd behavior with File.join on Ruby 2.0
  # So we go the long way around.
  (source.each_line.map do |l|
    if l.starts_with?('///') && !(m = %r!^///\s*<reference\s+path=(?:"([^"]+)"|'([^']+)')\s*/>\s*!.match(l)).nil?
      matched_path = m.captures.compact[0]
      l = l.sub(matched_path, File.join(escaped_dir, matched_path))
    end
    next l
  end).join
end