Created
January 27, 2017 01:36
-
-
Save sgoedecke/aaf25e5a56e9b1d5e15218bbe472b3ff 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
class StoredMethod | |
attr_accessor :result, :method, :args | |
def initialize(result, method, args) | |
@result = result | |
@method = method | |
@args = args | |
end | |
def execute(obj) | |
res = obj.send(@method, @args) | |
puts "executing #{@method} on #{obj.inspect} with #{@args}, got #{res}" | |
res | |
end | |
end | |
class StoredMethodChain | |
attr_accessor :result, :stored_methods | |
def initialize | |
@stored_methods = [] | |
end | |
def execute(obj) | |
last_result = obj | |
@stored_methods.each do |stored_method| | |
last_result = stored_method.execute(last_result) | |
end | |
last_result | |
end | |
end | |
class Mutator | |
def self.combine_procs(value, *procs) | |
last_result = value | |
procs.each do |proc| | |
last_result = proc.call(last_result) | |
end | |
last_result | |
end | |
def self.chain_random_methods(obj, num, excluded_results=[]) | |
last_result = obj | |
methods = StoredMethodChain.new | |
num.times do | |
res = self.random_method(last_result) while excluded_results.include?(res&.result) | |
last_result = res.result | |
methods.stored_methods << res | |
end | |
methods.result = last_result | |
methods | |
end | |
def self.random_argument(obj) | |
[obj, rand(999), rand(999).to_s].sample | |
end | |
def self.random_method(obj) | |
begin | |
method = (obj.methods - Object.methods).sample | |
argument = self.random_argument(obj) | |
result = obj.send(method, obj) | |
puts "executed #{method} on #{obj.inspect} with #{argument}, got #{result}" | |
rescue | |
self.random_method(obj) # do it until we get it right | |
end | |
StoredMethod.new(result, method, argument) | |
end | |
end | |
# puts Mutator.random_method("woof") | |
excluded_results = [nil, 0, [], false, true, ''] | |
method_chain = Mutator.chain_random_methods(5, 2, excluded_results) | |
puts method_chain.result.inspect | |
puts | |
puts | |
puts method_chain.execute(5).inspect | |
# puts Mutator.combine_procs "woof", Mutator.random_method("woof") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment