Created
October 23, 2010 21:32
-
-
Save Vaguery/642719 to your computer and use it in GitHub Desktop.
possibly foolish extension of String class to take optional parameters via a Hash
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
| # I'm inviting suggestions for refactoring this initialize method---without losing the fact that it's a subclass of String | |
| # should accept empty arguments; | |
| # should accept a string, and set default attributes; | |
| # should accept a string, with optional Hash args to set attributes; | |
| # should raise an error if there is no String but there is a Hash | |
| class ExtraString < String | |
| attr_accessor :optional_parameter | |
| def initialize(*args) | |
| if args[0].nil? | |
| super("") | |
| else | |
| raise ArgumentError, "ExtraString#new expected a String" unless args[0].kind_of?(String) | |
| super(args[0]) | |
| end | |
| @optional_parameter = args[1].nil? ? 100 : args[1][:bar] || 100 | |
| end | |
| end | |
| puts ExtraString.new.inspect # -> "" | |
| puts ExtraString.new.optional_parameter # -> 100 | |
| puts ExtraString.new("foo").inspect # -> "foo" | |
| puts ExtraString.new("foo").optional_parameter # -> 100 | |
| puts ExtraString.new("foo", bar:12).inspect # -> "foo" | |
| puts ExtraString.new("foo", bar:12).optional_parameter # -> 12 | |
| puts ExtraString.new("foo", baz:99).inspect # -> foo | |
| puts ExtraString.new("foo", baz:99).optional_parameter # -> 100 | |
| puts ExtraString.new(baz:99).inspect # raise an ArgumentError | |
| puts ExtraString.new(bar:13).optional_parameter # raise an ArgumentError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment