High-Performance, Dependency-Free Command Pattern For Ruby
gem 'riker', '0.1.0.pre6'
class SimpleGreeting
extend Riker
param :first_name
param :last_name, required: false
param :punctuation, default: '.'
execute do
if first_name == 'Voldemort'
errors.add(:first_name, 'He who shall not be named!')
return
end
return "Hello #{first_name}#{punctuation}" if last_name.nil?
"Hello #{first_name} #{last_name}#{punctuation}"
end
end
SimpleGreeting.run!(first_name: 'Will')
# => "Hello Will."
SimpleGreeting.run!(first_name: 'Will', last_name: 'Riker')
# => "Hello Will Riker."
SimpleGreeting.run!(first_name: 'Will', last_name: 'Riker', punctuation: '!')
# => "Hello Will Riker!"
SimpleGreeting.run!(first_name: 'Voldemort')
# => Riker::Outcome::ExecutionError => e
# => e.errors.messages == ['He who shall not be named!']
outcome = SimpleGreeting.run(first_name: 'Will')
outcome.valid?
# => true
outcome.result
# => "Hello Will."
outcome = SimpleGreeting.run(first_name: 'Voldemort')
outcome.invalid?
# => true
outcome.result
# => nil
outcome.errors.messages
# => ['He who shall not be named!']
class CaptainsLog
extend Riker
param :stardate, default: -> { Time.now.to_f }
param :message
execute do
"Captain's Log; Stardate: #{stardate}\n\n#{message}"
end
end
CaptainsLog.run!(message: "The Borg are attacking!")
# => "Captain's Log; Stardate: 1664393978.915553\n\nThe Borg are attacking!"
CaptainsLog.run(message: "We've traveled back in time!", stardate: 42.1337)
# => "Captain's Log; Stardate: 42.1337\n\nWe've traveled back in time!"
Sometimes you'll want to do some logic around your commands to record
their performance, number of calls, etc. Rike allows for this with around
.
The result of your measurement code in no way effects the result from
the command.
module SensorArray
class << self
# the class and args of the command are provided
def deep_scan(klass, args)
# anything before code runs
# code runs here
yield
# anything after you want
end
end
end
class CheckWarpDrive
extend Riker
param :stardate
param :engineer
around &SensorArray.method(:deep_scan)
execute do
"WarpDrive checked by #{engineer} on #{stardate}"
end
end