Created
July 12, 2018 23:40
-
-
Save sfgeorge/70f7561eacb924b13484944b01e124c2 to your computer and use it in GitHub Desktop.
Creative and weird ways to conditionally nest Ruby blocks, using the ruby_speech DSL as an example
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 'ruby_speech' | |
def append_phrase(document, phrase, options = {}) | |
build_phrase = Proc.new { prosody(rate: 1) { string phrase } } | |
if options[:voice_name] | |
document.embed RubySpeech::SSML.draw { voice(name: options[:voice_name], &build_phrase) } | |
else | |
document.embed RubySpeech::SSML.draw &build_phrase | |
end | |
document | |
end | |
root = RubySpeech::SSML.draw | |
#=> <speak version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/10/synthesis"/> | |
append_phrase root, 'I have a voice', voice_name: 'Frodo' | |
#=> <speak version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/10/synthesis"><voice name="Frodo"><prosody rate="1">I have a voice</prosody></voice></speak> | |
append_phrase root, 'I have no voice' | |
#=> <speak version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/10/synthesis"><voice name="Frodo"><prosody rate="1">I have a voice</prosody></voice><prosody rate="1">I have no voice</prosody></speak> | |
class Maybe | |
class << self | |
def maybe_voice(options = nil, &block) | |
if options | |
Proc.new { voice(options, &block) } | |
else | |
block | |
end | |
end | |
end | |
end | |
def append_phrase_2(document, phrase, voice_options = nil) | |
# document.embed RubySpeech::SSML.draw &Maybe::maybe_voice(voice_options) { prosody(rate: 1) { string phrase } } | |
document.embed RubySpeech::SSML.draw( | |
&::Maybe::maybe_voice(voice_options) do | |
prosody(rate: 1) do | |
string phrase | |
end | |
end | |
) | |
document | |
end | |
root2 = RubySpeech::SSML.draw | |
#=> <speak version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/10/synthesis"/> | |
append_phrase_2 root2, 'I have a voice', name: 'Frodo' | |
#=> <speak version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/10/synthesis"><voice name="Frodo"><prosody rate="1">I have a voice</prosody></voice></speak> | |
append_phrase_2 root2, 'I have no voice' | |
#=> <speak version="1.0" xml:lang="en-US" xmlns="http://www.w3.org/2001/10/synthesis"><voice name="Frodo"><prosody rate="1">I have a voice</prosody></voice><prosody rate="1">I have no voice</prosody></speak> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment