Skip to content

Instantly share code, notes, and snippets.

@saimonmoore
Created February 28, 2013 23:41
Show Gist options
  • Save saimonmoore/5061143 to your computer and use it in GitHub Desktop.
Save saimonmoore/5061143 to your computer and use it in GitHub Desktop.
Conditional execution
$ irb
>> class C
>> def self.opt?
>> true
>> end
>> end
=> nil
>>
?> module B
>> def foo
>> 'B'
>> end
>> end
=> nil
>>
?> module CB
>> def self.included(base)
>> puts 1
>> self.instance_methods.each do |meth|
?> puts "=======> meth: #{meth}"
>> alias_method "__#{meth}", meth
>> puts 2
>>
?> define_method meth do |*args|
?> puts 3
>> if C.opt?
>> puts 4
>> send("__#{meth}", *args)
>> else
?> puts 6
>> super(*args)
>> end
>> end
>> end
>> end
>>
?> def foo
>> 'CB'
>> end
>> end
=> nil
>>
?> class A
>> include B
>> include CB
>> end
1
=======> meth: foo
2
=> A
>>
?> puts "C.opt? => #{C.opt?}"
C.opt? => true
=> nil
>> a = A.new
=> #<A:0x007fad488142d0>
>>
?> puts a.foo
3
4
CB
=> nil
>>
?> class C
>> def self.opt?
>> false
>> end
>> end
=> nil
>>
?> puts "C.opt? => #{C.opt?}"
C.opt? => false
=> nil
>>
?> puts a.foo
3
6
B
=> nil
>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment