J
Jos Backus
Jos, we've talked about this two months ago on ruby-core. Maybe it's
only the syntax of libraries like "import-module" which you don't like,
but I think they can do what you want. See below.
Indeed we did.
Changing the interface of import-module to something like Tom's example,
here's your use case:
require "import-module-extended"
class Bar
extending(String) do
def foo
"the foo version of #{self.inspect}"
end
end
def initialize(name)
@name = name
end
def hello(name = nil)
name ||= @name
puts(name.foo)
end
end
b = Bar.new("Jos")
b.hello # => the foo version of "Jos"
b.hello("Pit") # => the foo version of "Pit"
b.hello(1) rescue puts "no Fixnum#foo" # => no Fixnum#foo
"Pit".foo rescue puts "no String#foo" # => no String#foo
You can see that #foo is added to String but is only visible within
class Bar. (The implementation is a quick and dirty hack, though.)
That's sweet! This does indeed seem to do what I'm looking for. Thanks Pit!
And Tom, too.
If I wanted this to be used inside class Baz, too, would I stick `foo' in a
module and use `extending' with that module somehow? I need to go check out
`import-module-extended'...
If it's a hacky implementation, how could it be cleaned up? This would be
great to have as part of stdlib.
Cheers,