Skip to content

Instantly share code, notes, and snippets.

@mathie
Created June 28, 2013 10:37
Show Gist options
  • Save mathie/5883835 to your computer and use it in GitHub Desktop.
Save mathie/5883835 to your computer and use it in GitHub Desktop.
Using .new as a factory method. Good idea or crazy?
class SerialNumber
def self.new(str = nil)
# Our new method is really a factory to one of the concrete subclasses.
if SerialNumber == self
if str.blank?
nil
# Zigbee serial numbers are easy to spot; they start with eight '0's.
elsif str.strip =~ /^00000000/
ZigbeeSerialNumber.new(str)
else
FtdiSerialNumber.new(str)
end
else
super
end
end
# general implementation
end
class FtdiSerialNumber < SerialNumber
# overridden implementation
end
class ZigbeeSerialNumber < SerialNumber
# overridden implementation
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment