|
Re: how to stop the subclass from overriding a method.: msg#02343ruby-talk
On Jul 30, 3:26 pm, Tim Pease <tim.pe...@xxxxxxxxx> wrote: > On Thu, Jul 30, 2009 at 1:19 PM, Robert Dober<robert.do...@xxxxxxxxx> wrote: > > On Thu, Jul 30, 2009 at 9:00 PM, Matt Neuburg<matt_neub...@xxxxxxxxxxx> > > wrote: > >> Venkat Akkineni <venkatram.akkin...@xxxxxxxxx> wrote: > > >>> Hi > > >>> How would one create a method that is accessible from > >>> outside but avoid the subclass from overriding and changing the > >>> definition? > > >> Something like this? > > >> class Superclass > >> def do_not_override > >> end > >> def self.method_added(s) > >> if s == :do_not_override > >> puts "Warning: you should not override this method" > >> else super > >> end > >> end > >> end > > >> That doesn't really prevent the programmer from working his will, but > >> then in Ruby *nothing* > > with the exception of freeze, but that is not applicable here as > > frozen classes can be subclassed without any problem and would be too > > radical anyway. > > But I thought if noteworthy that frozen objects and closures cannot be > > "cracked" in Ruby. > > An interesting little experiment I played a while ago regarding frozen > classes and modules. > > http://gist.github.com/82025 > > Does not address the original poster's question, but it might spur > some other creative thinking. One addition to this gist would be the > creation of an "inherited" method in the frozen class that would > subsequently freeze any class that tries to inherit from this. > Essentially this would make the class "un-inheritable" since > subclasses should not define any new methods. > > Blessings, > TwP xeno@amrita:~/projects$ irb -rmonkey >> class Test; def hello; puts "hello!"; end; end => nil >> monkey_proof Test => Test >> a = Test.new => #<Test:0x7f7c1db15008> >> a.hello hello! => nil >> a.extend Enumerable TypeError: can't modify frozen object from (irb):5:in `extend_object' from (irb):5:in `extend' from (irb):5 >> b = a.dup => #<Test:0x7f7c1dafb7c0> >> b.extend Enumerable => #<Test:0x7f7c1dafb7c0> :\ I do wonder though; maybe I've just had my head buried in Ruby too much these days, but in general, exactly what *is* the point of trying to restrict modification of your libraries? I understand 'private' and ish as a "hey, you probably don't have any reason to call me :\" sort of thing, but what does the library writer gain from trying to ensure their code won't be dynamically changed? Does this mostly just play into larger systems where your library is (or is part of) a larger framework, and as a curtesy you want to ensure that others parts of the system don't change you to avoid confusion? (if so, i apologize for the silly .dup jab there)
|
|
||||||||||||||||||||||||||
|
|
|
| News | Mail Home | sitemap | FAQ | advertise |