Created
August 30, 2015 04:51
-
-
Save chsh/6e1d170b7fe9a3e2ebbc to your computer and use it in GitHub Desktop.
Disable method execution by overriding "nothing to do" method.
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
module NOP | |
def self.nop(*args) | |
opts = args.extract_options! | |
methods = args | |
raise ArgumentError if methods.size < 2 | |
klass = methods.shift | |
raise ArgumentError unless klass.is_a?(Class) | |
do_backup, backup_prefix, backup_suffix = extract_backup_options opts[:backup] | |
methods.map(&:to_sym).each do |method| | |
next unless klass.instance_methods.include? method | |
result = opts[:return] || nil | |
if do_backup | |
backup_method = "#{backup_prefix}#{method}#{backup_suffix}" | |
klass.class_eval do | |
alias_method backup_method, method | |
end | |
end | |
klass.class_eval do | |
define_method method do |*args| | |
puts "NOP: #{method}, *args:#{args}, return:#{result}" | |
result | |
end | |
end | |
end | |
end | |
private | |
def self.extract_backup_options(value) | |
case value | |
when nil, FalseClass | |
[false, nil, nil] | |
when TrueClass | |
[value, '', '__'] | |
when String | |
raise ArgumentError if value.blank? | |
[true, nil, value] | |
when Hash | |
[true, | |
value[:prefix].presence || '', | |
value[:suffix].presence || '__'] | |
else raise ArgumentError | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment