Class: Synvert::Core::Engine::Slim

Inherits:
Object
  • Object
show all
Extended by:
Elegant
Defined in:
lib/synvert/core/engine/slim.rb

Constant Summary collapse

ATTRIBUTES_PAIR =
{ '{' => '}', '[' => ']', '(' => ')' }

Constants included from Elegant

Elegant::DO_BLOCK_REGEX, Elegant::ELSE_KEYWORDS, Elegant::END_LINE, Elegant::IF_KEYWORDS, Elegant::WHITESPACE

Class Method Summary collapse

Methods included from Elegant

generate_transform_proc, insert_end?, scan_ruby_expression, scan_ruby_interpolation_and_plain_text, scan_ruby_statement

Class Method Details

.encode(source) ⇒ String

Encode haml string, leave only ruby code, replace other haml code with whitespace. And insert end\n for each if, unless, begin, case to make it a valid ruby code.

Parameters:

  • source (String)

    haml code.

Returns:

  • (String)

    encoded ruby code.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/synvert/core/engine/slim.rb', line 16

def encode(source)
  leading_spaces_counts = []
  new_code = []
  scanner = StringScanner.new(source)
  loop do
    new_code << scanner.scan(/\s*/)
    leading_spaces_count = scanner.matched.size
    if scanner.scan('-') # it matches ruby statement "  - current_user"
      new_code << WHITESPACE
      scan_ruby_statement(scanner, new_code, leading_spaces_counts, leading_spaces_count)
    elsif scanner.scan(/==?/) # it matches ruby expression "  = current_user.login"
      new_code << (WHITESPACE * scanner.matched.size)
      scan_ruby_expression(scanner, new_code, leading_spaces_counts, leading_spaces_count)
    elsif scanner.scan(/[a-z#\.][a-zA-Z0-9\-_%#\.]*/) # it matches element, id and class "  span.user"
      new_code << (WHITESPACE * scanner.matched.size)
      ATTRIBUTES_PAIR.each do |start, ending| # it matches attributes in brackets "  span[ class='user' ]"
        scan_matching_wrapper(scanner, new_code, start, ending)
      end
      scan_attributes_between_whitespace(scanner, new_code)
      if scanner.scan(/ ?==?/) # it matches ruby expression "  span= current_user.login"
        new_code << ((WHITESPACE * (scanner.matched.size - 1)) + ';')
        scan_ruby_expression(scanner, new_code, leading_spaces_counts, leading_spaces_count)
      else
        scan_ruby_interpolation_and_plain_text(scanner, new_code, leading_spaces_counts, leading_spaces_count)
      end
    else
      scan_ruby_interpolation_and_plain_text(scanner, new_code, leading_spaces_counts, leading_spaces_count)
    end

    break if scanner.eos?
  end

  while leading_spaces_counts.pop
    new_code << END_LINE
  end
  new_code.join
end