[...]
If you have a klass#to_* method, you should have a
corresponding klass.from_* method if appropriate. This would
make your class more encapsulated, instead of having some of it
in String (or whatever class you are converting from).
Perhaps implement a method_missing in String such as s.to_xxx
will call xxx.from_s ?
--- "Kroeger Simon (ext)" <simon.kroeger.ext@siemens.com>
wrote:
> [...]
> If you have a klass#to_* method, you should have a
> corresponding klass.from_* method if appropriate. This
would
> make your class more encapsulated, instead of having some
of it
> in String (or whatever class you are converting from).
Perhaps implement a method_missing in String such as s.to_xxx
will call xxx.from_s ?
cheers
Simon
That sounds like a good idea to add a little convienence. That
shows the power of starting with the xxx.from_s(str) method
instead of String#to_xxx where the class is
embedded/abbreviated in the method name.
Here's a demo:
class String
def method_missing(meth)
if m = /^to_(.*)$/.match(meth.to_s)
Class.const_get(m[1].capitalize.to_sym).from_s(self)
else
super
end
end
end
class Abc
def self.from_s(s)
self.new(s)
end
def initialize(s) @abc = s
end
def to_s @abc.to_s
end
end
--- "Kroeger Simon (ext)" <simon.kroeger.ext@siemens.com>
wrote:
>
> > [...]
> > If you have a klass#to_* method, you should have a
> > corresponding klass.from_* method if appropriate. This
> would
> > make your class more encapsulated, instead of having some
> of it
> > in String (or whatever class you are converting from).
>
> Perhaps implement a method_missing in String such as
s.to_xxx
>
> will call xxx.from_s ?
>
> cheers
>
> Simon
That sounds like a good idea to add a little convienence.
That
shows the power of starting with the xxx.from_s(str) method
instead of String#to_xxx where the class is
embedded/abbreviated in the method name.
Here's a demo:
class String
def method_missing(meth)
if m = /^to_(.*)$/.match(meth.to_s)
Class.const_get(m[1].capitalize.to_sym).from_s(self)
else
super
end
end
end
class Abc
def self.from_s(s)
self.new(s)
end
def initialize(s) @abc = s
end
def to_s @abc.to_s
end
end