Created
July 22, 2012 19:14
-
-
Save alainravet/3160754 to your computer and use it in GitHub Desktop.
private_please : detect if a method can be made private
This file contains hidden or 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
| i - OUTSIDE CALL (calling this private method is normally forbidden) | |
| a_method was called | |
| i - INSIDE CALL | |
| a_method was called | |
| Process finished with exit code 0 |
This file contains hidden or 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 TraceFunHelper | |
| class << self | |
| attr_accessor :prev_prev_self, :prev_self, :curr_self | |
| @@prev_self = @@curr_self = nil | |
| end | |
| MY_TRACE_FUN = proc do |event, file, line, id, binding, klass| | |
| return unless 'line'==event | |
| TraceFunHelper.prev_prev_self = TraceFunHelper.prev_self | |
| TraceFunHelper.prev_self = TraceFunHelper.curr_self | |
| TraceFunHelper.curr_self = (eval 'self', binding) | |
| #puts "my : #{event} in #{file}/#{line} id:#{id} klass:#{klass} - self = #{(eval'self', binding).inspect}" | |
| end | |
| end | |
| set_trace_func(TraceFunHelper::MY_TRACE_FUN) | |
| def private_please(method_name) | |
| name = method_name | |
| orig_method = instance_method(name) | |
| define_method(name) do |*args, &blk| | |
| set_trace_func(nil) | |
| call_initiator = TraceFunHelper.prev_self | |
| if outside_call = call_initiator.class != self.class | |
| puts 'i - OUTSIDE CALL (calling this private method is normally forbidden)' | |
| else | |
| puts 'i - INSIDE CALL' | |
| end | |
| #puts "i - TraceFunHelper.curr_self = #{TraceFunHelper.curr_self.inspect}" | |
| #puts "i - TraceFunHelper.prev_self = #{TraceFunHelper.prev_self.inspect}" | |
| #puts "i - TraceFunHelper.prev_prev_self = #{TraceFunHelper.prev_prev_self.inspect}" | |
| # make the call | |
| orig_method.bind(self).call(*args, &blk) | |
| set_trace_func(TraceFunHelper::MY_TRACE_FUN) | |
| end | |
| end | |
| #--------------#--------------#--------------#--------------#--------------#-------------- | |
| class Foo | |
| def butler ; a_method end | |
| def a_method ; puts 'a_method was called' end | |
| private_please :a_method | |
| end | |
| Foo.new.a_method | |
| Foo.new.butler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment