Skip to content

Instantly share code, notes, and snippets.

@jqmtor
Last active December 26, 2015 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jqmtor/47c4c2c71e346494653c to your computer and use it in GitHub Desktop.
Save jqmtor/47c4c2c71e346494653c to your computer and use it in GitHub Desktop.
Initialize object without new
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