Last active
December 26, 2015 11:49
-
-
Save jqmtor/47c4c2c71e346494653c to your computer and use it in GitHub Desktop.
Initialize object without new
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
class Team | |
attr_accessor :name, :country | |
class << self | |
undef_method :new | |
end | |
def self.constructor(*args) | |
obj = allocate | |
obj.send(:initialize, *args) | |
obj | |
end | |
end | |
class Barcelona < Team | |
def initialize(name, country) | |
@name = name | |
@country = country | |
end | |
end | |
class ChicagoBulls < Team | |
def initialize(name, city, country) | |
@name = name | |
@city = city | |
@country = country | |
end | |
end | |
require 'test/unit' | |
class TestBarcelonaTeam < Test::Unit::TestCase | |
def test_initialize_barcelona | |
team = Barcelona.constructor("Barcelona", "Spain") | |
assert team.is_a? Team | |
end | |
def test_initialize_chicago | |
team = ChicagoBulls.constructor("Chicago Bulls", "Chicago", "United States") | |
assert team.is_a? Team | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment