Skip to content

Instantly share code, notes, and snippets.

@Supernats
Last active January 15, 2018 23:23
Show Gist options
  • Save Supernats/62b065c85a4a5eb7cfafb2956b038b83 to your computer and use it in GitHub Desktop.
Save Supernats/62b065c85a4a5eb7cfafb2956b038b83 to your computer and use it in GitHub Desktop.
# rubocop:disable Style/Alias
# rubocop:disable Style/Documentation
# rubocop:disable Lint/UnneededSplatExpansion
require 'pry'
Thread.abort_on_exception = true
class ThreadGroupsMadeEasy
def self.in_thread_group(thread_group, &block)
thread = Thread.new(&block)
thread_group.add(thread)
thread
end
def self.new(*_args)
raise 'This is not meant to be instantiated.'
end
end
class Chant
def initialize(options = self.class.default_options)
self.class.default_options.merge(options).each do |attribute, value|
instance_variable_set("@#{attribute}".to_sym, value)
end
end
def call
ThreadGroupsMadeEasy.in_thread_group(thread_group) do
loop do
ThreadGroupsMadeEasy.in_thread_group(thread_group) { say_the_thing }
sleep delay
end
end
self
end
def silence!
thread_group.list.each(&:exit)
end
alias_method :chant, :call
private
attr_reader(
*%i[
count
delay
phrase
speed
voice
]
)
def thread_group
@thread_group ||= ThreadGroup.new
end
def say_the_thing
IO.popen("say -r #{speed} -v \"#{voice}\"", 'w') { |io| io.write(phrase) }
end
class << self
def call(opts = {})
new(opts).call
end
alias_method :chant, :call
# Shouldn't be needed, but sometimes you want to kill those threads.
# Was helpful in early development.
def kill
Thread.list.each do |thread|
thread.exit unless thread == Thread.current
end
end
def phrases
{
fhtagn: "Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn"
}
end
def default_options
{
count: 3,
delay: 3,
phrase: phrases[:fhtagn],
speed: 200,
voice: 'Pipe Organ'
}
end
end
end
foo = Chant.new(count: 7, delay: 2, speed: 80)
puts 'The chanting shall now commence. Enter "y" to stop it.'
foo.chant
sleep until gets.chomp.casecmp('y').zero?
foo.silence!
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment