Created
March 21, 2011 21:35
-
-
Save fabrizioc1/880266 to your computer and use it in GitHub Desktop.
The difference between extend and include in Ruby
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 'test/unit' | |
require 'active_support/all' | |
class TestExtendAndInclude < Test::Unit::TestCase | |
module SomethingExtended | |
mattr_accessor :data_attributes | |
def data_attribute(name) | |
self.data_attributes ||= [] | |
self.data_attributes << name | |
attr_accessor name | |
end | |
end | |
module SomethingIncluded | |
def self.included(base) | |
base.class_attribute :data_attributes | |
base.data_attributes = [] | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def data_attribute(name) | |
self.data_attributes << name | |
attr_accessor name | |
end | |
end | |
end | |
class StuffExtendsSomething | |
extend SomethingExtended | |
data_attribute :message | |
end | |
class StuffIncludesSomething | |
include SomethingIncluded | |
data_attribute :message | |
end | |
def setup | |
@x = StuffExtendsSomething.new | |
@y = StuffIncludesSomething.new | |
@x.message = "hello" | |
@y.message = "hello" | |
end | |
def test_that_they_both_define_the_same_attribute | |
assert_equal(@x.message,@y.message, | |
"both classes should have the same value for :message") | |
end | |
def test_that_they_both_have_the_same_class_attributes | |
assert_equal(@x.class.data_attributes,@y.class.data_attributes, | |
"both classes should have the same data attributes") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment