ptkwt
10/20/2003 5:28:00 PM
In article <20031020164547.GB28386@mulan.thereeds.org>,
Mark J. Reed <markjreed@mail.com> wrote:
>On Mon, Oct 20, 2003 at 09:29:42AM -0700, John wrote:
>> Right now I can do that by doing
>>
>> def gsub!(match, replacewith)
>> @s = @s.gsub!(match, replacewith)
>> end
>>
>> but this seems clunky.
>
>It's clunky if you really do want to just pass on most method calls
>unchanged to the included String. In that case inheritance is better.
>Although composition of the sort you refer to above is often cleaner,
>and you can use method_missing to forward methods by default without
>having to write duplicates like that.
>
>> If I make Template a subclass of String, I could just use gsub directly.
>
>Yup.
>
>> My question is, how to do this?
>
>Well, if you make Template a subclass of String, you don't have to do
>anything. Once you've done
>
> class Template < String; end
>
>then you can call .gsub! on any Template instance automatically.
>
However, then you can't use "", '', etc. to construct strings like so:
str = "this is a string/template"
Maybe that's not a big deal for your application, though.
>But if you want to manipulate the string data within a method, just use "self":
>
> class Template < String
> def applySubstitutions(valuesHash)
> valuesHash.each do
> |key, value|
> self.gsub!(/@{#{key}}/, value)
> end
> end
> end
>
Alternatively, you could extend String by adding the methods you need to
it. I know it's not considered as 'safe' or 'correct' in some circles,
but that's probably the way I'd be inclined to go.
class String
def your_added_method
#...
end
end
Or alternatively, you could put your added methods into a module and then
mix them into String.
Phil