Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require "rubygems"
require "colorize"
def desc(msg)
puts "Description".colorize(:yellow)
puts "===========".colorize(:yellow)
puts msg.colorize(:white)
end
def example(body)
puts "\nRunning:".colorize(:yellow)
body.each_line do |line|
puts " #{line}"
end
result = eval(body)
puts "Success! Result is #{result.inspect}".colorize(:green)
rescue Exception => e
puts "Failed! Exception is #{e.class}: #{e.message}".colorize(:red)
ensure
puts "\n"
end
desc "Including a module into a class makes it's instance methods available to the class and it's subclasses"
example <<EOR
module Groot
def groot
"I am groot"
end
end
class A
include Groot
end
A.groot
EOR
example <<EOR
module Groot
def groot
"I am groot"
end
end
class A
include Groot
end
A.new.groot
EOR
example <<EOR
module Groot
def groot
"I am groot"
end
end
class A
include Groot
end
class B < A
end
B.new.groot
EOR
desc "Extending a module onto a class makes it's instance methods available as class methods"
example <<EOR
module Groot
def groot
"I am groot"
end
end
class A
extend Groot
end
A.groot
EOR
example <<EOR
module Groot
def groot
"I am groot"
end
end
class A
extend Groot
end
A.new.groot
EOR
desc "You can't call `include` on a class instance, but can call `extend`"
example <<EOR
module Groot
def groot
"I am groot"
end
end
class A
end
A.new.include(Groot).groot
EOR
example <<EOR
module Groot
def groot
"I am groot"
end
end
class A
end
A.new.extend(Groot).groot
EOR
desc "included modules are added between a class and it's superclass in the ancestor chain"
example <<EOR
class SuperClass
end
module ExampleModule
end
class SubClass < SuperClass
include ExampleModule
end
SubClass.ancestors
EOR
desc "prepended modules are added **before** a class in the ancestor chain"
example <<EOR
class SuperClass
end
module ExampleModule
end
class PrependedSubClass < SuperClass
prepend ExampleModule
end
PrependedSubClass.ancestors
EOR
desc "extended modules are not added to the classes ancestor chain (google \"Ruby Eigenclass\" if you want to know where they go)"
example <<EOR
class SuperClass
end
module ExampleModule
end
class ExtendedSubClass < SuperClass
extend ExampleModule
end
ExtendedSubClass.ancestors
EOR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.