Class: Rasputin::RequirePreprocessor

Inherits:
Tilt::Template
  • Object
show all
Defined in:
lib/rasputin/require_preprocessor.rb

Constant Summary collapse

REQUIRE_PATTERN =
/require\(\s*['"]([^\)]+)['"]\s*\)\s*;?\s*/
HEADER_PATTERN =
/
  \A (
    (?m:\s*) (
      (\/\* (?m:.*?) \*\/) |
      (\#\#\# (?m:.*?) \#\#\#) |
      (\/\/ .* \n?)+ |
      (\# .* \n?)+ |
      (#{REQUIRE_PATTERN} \n?)+
    )
  )+
/x
DIRECTIVE_PATTERN =
/^\s*#{REQUIRE_PATTERN}$/
TREE_PATTERN =
/\*\*\/\*$/
DIRECTORY_PATTERN =
/\*$/

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



22
23
24
# File 'lib/rasputin/require_preprocessor.rb', line 22

def body
  @body
end

#headerObject (readonly)

Returns the value of attribute header.



22
23
24
# File 'lib/rasputin/require_preprocessor.rb', line 22

def header
  @header
end

#pathnameObject (readonly)

Returns the value of attribute pathname.



21
22
23
# File 'lib/rasputin/require_preprocessor.rb', line 21

def pathname
  @pathname
end

Instance Method Details

#directivesObject



68
69
70
71
72
73
74
75
76
77
# File 'lib/rasputin/require_preprocessor.rb', line 68

def directives
  @directives ||= header.lines.each_with_index.map { |line, index|
    if line =~ DIRECTIVE_PATTERN
      name, path = detect_directive($1)
      if respond_to?("process_#{name}_directive")
        [index + 1, name, path]
      end
    end
  }.compact
end

#evaluate(context, locals, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/rasputin/require_preprocessor.rb', line 40

def evaluate(context, locals, &block)
  if @enable
    @context = context
    process_directives

    processed_source
  else
    body
  end
end

#prepareObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rasputin/require_preprocessor.rb', line 24

def prepare
  @pathname = Pathname.new(file)

  @enable = Rails.configuration.rasputin.enable
  @strip_require_directives = Rails.configuration.rasputin.strip_require_directives

  if @enable
    @header = data[HEADER_PATTERN, 0] || ""
    @body   = $' || data
    # Ensure body ends in a new line
    @body  += "\n" if @body != "" && @body !~ /\n\Z/m
  else
    @body = data
  end
end

#processed_headerObject



51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rasputin/require_preprocessor.rb', line 51

def processed_header
  if @enable && @strip_require_directives
    lineno = 0
    @processed_header ||= header.lines.map { |line|
      lineno += 1
      # Replace directive line with a clean break
      directives.assoc(lineno) ? "\n" : line
    }.join.chomp
  else
    @processed_header ||= header.chomp
  end
end

#processed_sourceObject



64
65
66
# File 'lib/rasputin/require_preprocessor.rb', line 64

def processed_source
  @processed_source ||= processed_header + "\n" + body
end