Last active
March 9, 2018 14:11
-
-
Save cadamini/2a67741f5138cb9f8db22d2a75ffbf03 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pp' | |
require 'open-uri' | |
class LinkFinder | |
def initialize(folder:, regex:) | |
@folder = folder | |
@regex = regex | |
end | |
def scan_files | |
Dir[@folder].each_with_index do |file, index| | |
file_content = ContentAnalyzer.new(file: file) | |
urls = file_content.analyze(@regex) | |
unless urls.empty? | |
# get url array and return single string | |
urls.each_with_index do |match, index| | |
url = match[0] | |
# use string in open() | |
open(url) do |u| | |
# use file and index in create_file | |
File.open( | |
"img/#{File.basename(file)}-#{index}.png", 'wb' | |
) { |f| f.write(u.read) } | |
end | |
replaced_content = file_content.content.gsub(match[0], "/assets/img/#{File.basename(file)}-#{index}.png") | |
File.open(file, "w") {|file| file.puts replaced_content} | |
end | |
end | |
end | |
end | |
end | |
class ContentAnalyzer | |
attr_accessor :content | |
def initialize(file:) | |
@content = File.read(file) | |
end | |
def analyze(regex) | |
@content.scan(regex) | |
end | |
end | |
LinkFinder.new( | |
folder: '/Users/cadamini/testfolder/_docs/*', | |
regex: /(https:\/\/(lh[0-9].|docs.google.com\/)([^\s)"]+))/ | |
).scan_files |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment