# require an external module (ruby standard in ths case). At the top-level, # so it's methods are available everywhere. require "fileutils" # Lets' mix a new method into an existing class, 'Class' module NewClassMethod def new_attr_accessor(*syms) puts "Making accessors: #{syms.inspect}" attr_accessor *syms end end class Class include NewClassMethod end # Make our own module to include in a new class module MyFileUtils def print_wd puts "#{self.class.name} #{self.object_id} (#{self.to_s})", "Workdir: #{FileUtils.pwd()}" end end class MyClazz # Right now, 'self' is a class, so we can call our new class method new_attr_accessor :myattr include MyFileUtils # require is just a method, and can be called anywhere. # but the scoping remains the same as any other code. require 'requireme.rb' # Call our new method on 'Object' def call_new_method Object.new.new_method end end # The included methods *do* become part of the class they're included to. b = MyClazz.new b.print_wd # The methods added to Object are available of course on every Object, # since redefining a class always redefines that class. p b.call_new_method p Object.new.new_method # Our 'other method' (a straight def in requireme) is defined on Kernel, # which mixes in private methods to every class, so we can't call it # like: begin b.other_method rescue NoMethodError => ex puts "Got expected #{ex}" end # We could to resort to 'send' if we really care. p b.send(:other_method) # But, since it's a private kernel method the intention is really # that it be called only without a receiver. p other_method # This won't print 'REQUIRED' again - 'require' only loads stuff once. # If you wanted to have it loaded again and again, you could use 'load' # instead. 10.times { require 'requireme' }