Guest User

Untitled

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