hqt

Ruby custom extend/include

hqt
Feb 4th, 2017
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.34 KB | None | 0 0
  1. # created by Huynh Quang Thao
  2. # on 02/04/2017
  3. require 'test/unit'
  4.  
  5. # ------------------------------------------------------------
  6. # implementation
  7. class Class
  8.   def custom_include(module_name)
  9.     module_name.instance_methods.each do |method|
  10.       puts method
  11.       define_method(method) do |*args, &block|
  12.         # my fault. cannot send here. because module cannot be initialized
  13.         module_name.send(method, *args, &block)
  14.       end
  15.     end
  16.   end
  17.  
  18.   def custom_extend(module_name)
  19.     module_name.methods(false).each do |method|
  20.       define_singleton_method(method) do |*args, &block|
  21.         module_name.send(method, *args, &block)
  22.       end
  23.     end
  24.   end
  25. end
  26.  
  27. # -------------------------------------------------------------
  28. # Demonstration
  29. module SimpleModule
  30.   def self.class_hello_world
  31.     puts 'i am a simple module boss'
  32.   end
  33.  
  34.   def hello_world
  35.     puts 'i am a simple module client'
  36.   end
  37. end
  38.  
  39. class SimpleClass
  40.   custom_include SimpleModule
  41.   custom_extend  SimpleModule
  42. end
  43.  
  44. SimpleClass.class_hello_world
  45.  
  46. # -----------------------------------------------------------------
  47. # Testing
  48. class TestUsing < Test::Unit::TestCase
  49.   def test_custom_extend
  50.     message = SimpleClass.class_hello_world
  51.     assert message == SimpleModule.class_hello_world
  52.   end
  53. end
  54.  
  55. TestUsing.new("test extend/include")
Advertisement
Add Comment
Please, Sign In to add comment