Skip to content

Instantly share code, notes, and snippets.

@wojtha
Created August 3, 2018 15:56
Show Gist options
  • Save wojtha/139b19f4963038ea58ad7c9eab3e10ba to your computer and use it in GitHub Desktop.
Save wojtha/139b19f4963038ea58ad7c9eab3e10ba to your computer and use it in GitHub Desktop.
How to dispatch `self.new` to subclasses and not end up with stack level too deep error...
module Steps
class Step
DEFAULT_VERSION = 2
def self.new(attrs = {})
version = attrs.fetch(:step_version, DEFAULT_VERSION)
klass = "StepV#{version}".constantize
klass.new(attrs)
end
end
class StepV2 < Step
def self.new(*args)
obj = allocate
obj.send(:initialize, *args)
obj
end
def step_version
2
end
end
class StepV3 < Step
def self.new(*args)
obj = allocate
obj.send(:initialize, *args)
obj
end
def step_version
3
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment