Module: Deface::Applicator::ClassMethods

Included in:
Override
Defined in:
lib/deface/applicator.rb

Instance Method Summary collapse

Instance Method Details

#apply(source, details, log = true, syntax = :erb) ⇒ Object

applies all applicable overrides to given source



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/deface/applicator.rb', line 6

def apply(source, details, log=true, syntax=:erb)
  overrides = find(details)

  return source if overrides.empty?

  Rails.logger.debug "\e[1;32mDeface:\e[0m #{overrides.size} overrides found for '#{details[:virtual_path]}'" if log

  apply_overrides(
    convert_source(source, syntax: syntax),
    overrides: overrides,
    log: log
  )
end

#apply_overrides(source, overrides:, log: true) ⇒ Object

applies specified overrides to given source



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
53
54
55
56
57
# File 'lib/deface/applicator.rb', line 21

def apply_overrides(source, overrides:, log: true)

  doc = Deface::Parser.convert(source)

  overrides.each do |override|
    if override.disabled?
      Rails.logger.debug("\e[1;32mDeface:\e[0m '#{override.name}' is disabled") if log
      next
    end

    override.parsed_document = doc
    matches = override.matcher.matches(doc, log)

    if log
      Rails.logger.send(matches.size == 0 ? :error : :debug, "\e[1;32mDeface:\e[0m '#{override.name}' matched #{matches.size} times with '#{override.selector}'")

      # temporarily check and notify on use of old selector styles.
      #
      if matches.empty? && override.selector.match(/code|erb-loud|erb-silent/)
        Rails.logger.error "\e[1;32mDeface: [WARNING]\e[0m Override '#{override.name}' may be using an invalid selector of '#{override.selector}', <code erb-loud|silent> tags are now <erb loud|silent>"
      end
    end

    if matches.empty?
      override.failure = "failed to match :#{override.action} selector '#{override.selector}'"
    else
      override.failure = nil
      matches.each {|match| override.execute_action match }
    end
  end

  source = doc.to_s

  Deface::Parser.undo_erb_markup!(source)

  source
end

#convert_source(source, syntax:) ⇒ Object

converts the source to a supported syntax (ERB)



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/deface/applicator.rb', line 60

def convert_source(source, syntax:)
  # convert haml/slim to erb before parsing before
  case syntax
  when :erb
    source
  when :haml
    Deface::HamlConverter.new(source.to_s).result
  when :slim
    Deface::SlimConverter.new(source.to_s).result
  else
    raise "unsupported syntax: #{syntax}"
  end
end