Guest User

Untitled

a guest
May 24th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. class Module
  2. def deprecate(sym, scope=nil)
  3. meth = instance_method(sym)
  4. unless scope
  5. pub = public_instance_methods
  6. pro = protected_instance_methods
  7. pri = private_instance_methods
  8. if pub.include?(sym) or pub.include?(sym.to_s)
  9. scope = :public
  10. elsif pro.include?(sym) or pro.include?(sym.to_s)
  11. scope = :protected
  12. elsif pri.include?(sym) or pri.include?(sym.to_s)
  13. scope = :private
  14. end
  15. end
  16.  
  17. define_method(sym) do |*args|
  18. dep_meth = method(sym).unbind
  19. __deprecated_run_hook__(sym)
  20. retval = meth.bind(self).call(*args)
  21. dep_meth.bind(self)
  22. return retval
  23. end
  24.  
  25. method(scope).call(sym) if scope
  26. return scope
  27. end
  28. end
  29.  
  30. module Deprecated
  31. def __deprecated_run_hook__(sym)
  32. if @__deprecated_run_hook__
  33. @__deprecated_run_hook__.call(self.class, sym)
  34. else
  35. Deprecated.run_hook(self.class, sym)
  36. end
  37. end
  38.  
  39. def deprecated_set_hook(&block)
  40. raise "blah" unless block_given?
  41. @__deprecated_hook__ = block.to_proc
  42. end
  43.  
  44. def self.set_hook(type=nil, &block)
  45. @hook = case type
  46. when :warn
  47. proc { |klass, sym| warn "#{klass}##{sym} is deprecated." }
  48. when :die
  49. proc { |klass, sym| "stuff" }
  50. when :raise
  51. proc { |klass, sym| "stuff" }
  52. else
  53. raise "blah"
  54. end
  55. end
  56.  
  57. def self.run_hook(klass, sym)
  58. raise "no hook" unless @hook
  59. @hook.call(klass, sym)
  60. end
  61. end
  62.  
  63. class Foo
  64. include Deprecated
  65.  
  66. def foo
  67. "bar"
  68. end
  69.  
  70. deprecate :foo
  71. end
  72.  
  73. Deprecated.set_hook(:warn)
  74.  
  75. p Foo.new.foo
Add Comment
Please, Sign In to add comment