Created
October 5, 2011 19:17
-
-
Save danreedy/1265373 to your computer and use it in GitHub Desktop.
Module include vs extend test. Developing a Rails engine and I want to add a method that all ActiveRecord objects will respond to when called. Refactored to use a single include
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest/autorun' | |
module KnightIndustries | |
def self.included (klass) | |
klass.extend ClassMethods | |
end | |
def can_talk? | |
false | |
end | |
module ClassMethods | |
def built_by_knight | |
include KnightIndustriesMethods | |
end | |
end | |
module KnightIndustriesMethods | |
def can_talk? | |
true | |
end | |
def goes | |
"Hello, Michael" | |
end | |
end | |
end | |
class Car | |
def goes | |
"Vroom Vroom" | |
end | |
end | |
Car.send(:include, KnightIndustries) | |
class Kitt < Car | |
built_by_knight | |
end | |
describe Car do | |
before do | |
@hyundai = Car.new | |
end | |
it "should not talk" do | |
@hyundai.can_talk?.must_equal false | |
end | |
it "should say 'Vroom Vroom'" do | |
@hyundai.goes.must_equal "Vroom Vroom" | |
end | |
end | |
describe Kitt do | |
before do | |
@kitt = Kitt.new | |
end | |
it "should talk" do | |
@kitt.can_talk?.must_equal true | |
end | |
it "should say 'Hello, Michael'" do | |
@kitt.goes.must_equal "Hello, Michael" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment