Created
March 6, 2019 10:20
-
-
Save alexandreprates/1e8de12b5d4d449a22d9b424fae9eb80 to your computer and use it in GitHub Desktop.
Ruby factory example
This file contains hidden or 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 Driver | |
class << self | |
def list | |
@list ||= {} | |
end | |
def add_subclass(subclass_name, subclass) | |
list.store subclass_name, subclass | |
puts "Added subclass #{subclass_name} -> #{subclass}" | |
end | |
def inherited(subclass) | |
name = subclass.name.downcase | |
self.add_subclass(name.to_sym, subclass) | |
end | |
end | |
module Factory | |
class << self | |
def [](name) | |
Driver.list[name] || Driver | |
end | |
end | |
end | |
end | |
class SuperDuper < Driver | |
end | |
class Bubbles < Driver | |
end | |
puts Driver.list | |
p Driver::Factory[:superduper].new | |
p Driver::Factory[:bubbles].new | |
p Driver::Factory[:oopsy].new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment