Skip to content

Instantly share code, notes, and snippets.

@alexandreprates
Created March 6, 2019 10:20
Show Gist options
  • Save alexandreprates/1e8de12b5d4d449a22d9b424fae9eb80 to your computer and use it in GitHub Desktop.
Save alexandreprates/1e8de12b5d4d449a22d9b424fae9eb80 to your computer and use it in GitHub Desktop.
Ruby factory example
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