Is there a way to restrict the visibility of changes to standard classes
and modules? I commonly use some extensions of standard classes. Now,
when I release my code as a library I’d have to include these
extensions and anyone using my lib would get them nilly-willy.
I very much like the ability to extend existing classes, but I don’t
want to inflict my changes on others.
I know David Black’s “behaviors”, but they are dynamically scoped.
What’s needed is a statically scoped approach to namespace cleanliness.
I’m not sure if I understand it correctly, but I don’t think it can do
what I want. Here’s an exemplary case
File myexts.rb
module MyExts
class String
def starts_with(s)
index(s) == 0
end
def ends_with(s)
index(s, -(s.length)) != nil
end
def without_prefix(p)
return self unless self.starts_with(p)
self[p.length…-1]
end
end
end
File somelib.rb
require ‘myexts’
module SomeLib
def some_method(s)
if s.starts_with(“…”)
…
end
end
end
File libuser.rb
require ‘somelib’
class C
include SomeLib
…
end
Now, within libuser.rb I don’t want the definitions from myexts.rb to be
visible.
Here’s the catch. ‘Require’ is transitive. When I ‘require’ something,
I’ll get everything that was recursively required, even stuff that is
only needed internally within the module/class I really want.