Skip to content

Instantly share code, notes, and snippets.

@bodrovis
Created December 3, 2023 19:18
Show Gist options
  • Save bodrovis/d3389deb363e19a8deec36d1eef6d053 to your computer and use it in GitHub Desktop.
Save bodrovis/d3389deb363e19a8deec36d1eef6d053 to your computer and use it in GitHub Desktop.
# demo.rb
ts = (1..5).map do |i|
Thread.new do
sleep(1)
puts "done #{i}"
Thread.current.kill if i == 3
rand(1..100)
end
end
puts 'starting...'
#begin
results = ts.map(&:value)
# rescue => e
# puts "EXCEPTION"
# puts e.inspect
# end
puts 'done with threads'
puts results.inspect
# kram.rb
require 'kramdown'
require 'pathname'
class Converter
attr_reader :threads
def initialize(folder = 'md', in_ext = '.md')
@folder = folder
@in_ext = in_ext
@threads = []
end
def convert!
each_file do |file|
puts "Starting with #{file}"
in_thread do
converted_data = do_convert File.read(file)
save converted_data, file.basename(@in_ext)
end
puts "Next file..."
end
@threads.map(&:value)
end
private
def save(data, filename)
path = File.expand_path("./html/#{filename}.html", __dir__)
File.open(path, 'w:UTF-8') do |f|
f.write data
end
path
end
def do_convert(data)
sleep 1
Kramdown::Document.new(data).to_html
end
def in_thread(&block)
@threads << Thread.new(&block)
end
def each_file
return unless block_given?
Dir.glob("#{@folder}/*#{@in_ext}").each do |file|
yield Pathname.new(File.expand_path(file, __dir__))
end
end
end
converter = Converter.new
results = converter.convert!
puts converter.threads
puts results.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment