Class: Image::SourceCodeScrubber

Inherits:
Object
  • Object
show all
Defined in:
app/services/image/source_code_scrubber.rb

Overview

Goal: parse heatwave's source code .erb and .rb
extract any URL references/string using IMG_URL
Find image by slug
Convert to appropriate image url using IK_URL

Constant Summary collapse

PATTERNS =
[]

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#touched_filesObject (readonly)

Returns the value of attribute touched_files.



12
13
14
# File 'app/services/image/source_code_scrubber.rb', line 12

def touched_files
  @touched_files
end

Instance Method Details

#process(file_list = []) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/services/image/source_code_scrubber.rb', line 14

def process(file_list = [])
  @touched_files = []
  if file_list.blank?
    file_list = Dir['{app,client}/**/*.{css,scss,js,rb,erb,}']
    file_list += Dir['config/initializers/*.rb']
  end
  file_list.each do |file_name|
    puts file_name
    scrub_file(file_name)
  end
  @touched_files
end

#scrub_content(content, file_name) ⇒ Object

e.g [https://ik.warmlyyours.com/img/pipe-freeze-protection-header-8ab914.png?hello-world"]?tr=w-1140,h-290,cm-pad_resize,bg-FFFFFF
Will be matched like

  1. w-1140,h-290,cm-pad_resize,bg-FFFFFF
  2. pipe-freeze-protection-header-8ab914.png?hello-world


36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/services/image/source_code_scrubber.rb', line 36

def scrub_content(content, file_name)
  content_replaced = false
  scrubbed_content = content.dup
  PATTERNS.each do |pattern|
    scrubbed_content.gsub!(pattern) do |match_string|
      puts "#{file_name} -> /#{pattern}/ -> #{match_string}"
      processing_string, file_id = match_string.scan(pattern)&.first
      # replaced_string = Image::LegacyImageParamTranslator.translate_from_components(processing_string, file_id, file_format)
      replaced_string = "https://ik.warmlyyours.com/img/#{file_id}?tr=#{processing_string}"
      touched_files << { file_id:, match_string:, processing_string:, replaced_string: }
      content_replaced = true
      quote = nil
      quote = "'" if match_string[0] == "'"
      quote = '"' if match_string[0] == '"'
      "#{quote}#{replaced_string}#{quote}"
    end
  end
  if content_replaced
    File.open(file_name, 'w') do |file|
      file.puts scrubbed_content
      file.flush
      file.fsync
    end
  end
  scrubbed_content
end

#scrub_file(file_name) ⇒ Object



27
28
29
30
# File 'app/services/image/source_code_scrubber.rb', line 27

def scrub_file(file_name)
  content = File.read(file_name)
  scrub_content(content, file_name)
end