instance_wrapper.rb 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. module Mixin
  2. # This modules enables to redirect all calls to methods that are
  3. # not defined to the declared instance variable. This comes handy
  4. # when you wan't extend a Ruby core class like Hash.
  5. # To inherit directly from such classes is a bad idea and should be avoided.
  6. # This way allows it indirectly.
  7. module InstanceWrapper
  8. module ClassMethods
  9. # Creates the class macro `wrap` that activates
  10. # the wrapping for the given instance variable name.
  11. #
  12. # @param [Symbol] variable the name of the instance variable to wrap around
  13. #
  14. # @example
  15. # wrap :@some_hash
  16. #
  17. # @return [nil]
  18. def wrap(variable)
  19. define_method(:instance) do
  20. instance_variable_get(variable)
  21. end
  22. end
  23. end
  24. def self.included(base)
  25. base.extend(ClassMethods)
  26. end
  27. private
  28. def method_missing(method, *args, &block)
  29. if instance.respond_to?(method)
  30. instance.send(method, *args, &block)
  31. else
  32. super
  33. end
  34. end
  35. def respond_to_missing?(method_sym, include_all)
  36. instance.respond_to?(method_sym, include_all)
  37. end
  38. end
  39. end