Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #7140

Re: Alternative Way to Refine A Class

Newsgroups comp.lang.ruby
Date 2015-09-18 07:54 -0700
References <1527382d-cf5c-429a-ac5d-59569b710f69@googlegroups.com>
Message-ID <4896229f-e47e-4779-83eb-a25eddb506b4@googlegroups.com> (permalink)
Subject Re: Alternative Way to Refine A Class
From lha <luisealvarezb@gmail.com>

Show all headers | View raw


        # Injector declaration

        jack :StringRefinements do
           lets String do                            # Our re-classing
              with singleton_class do
                 def new *args, &code
                    super(*args, &code) + ' is a special string'
                 end
              end
           end
        end

        class OurClass
           include StringRefinements()

           def foo_bar
              String('foo and bar')
           end
        end

        c = OurClass.new
        c.foo_bar.class.should == String
        c.foo_bar.should == 'foo and bar is a special string'

        StringRefinements do
           String() do                              # Adding more stuff
              def extra
                 :extra
              end
           end
        end

        c.foo_bar.should == 'foo and bar is a special string'
        c.foo_bar.extra.should == :extra

        SR = StringRefinements do
           lets String do                           # New Version
              def to_s
                 super + '****'
              end
           end
        end

        # c is still the same

        c.foo_bar.should == 'foo and bar is a special string'
        c.foo_bar.extra.should == :extra


        class OurOtherClass
           include SR                       # Another class application


           def foo_bar
              String('foo and bar')
           end
        end

        d = OurOtherClass.new

        d.foo_bar.to_s.should == 'foo and bar****'
        expect{ d.extra }.to raise_error(NoMethodError)

Back to comp.lang.ruby | Previous | NextPrevious in thread | Find similar


Thread

Alternative Way to Refine A Class lha <luisealvarezb@gmail.com> - 2015-09-09 12:00 -0700
  Re: Alternative Way to Refine A Class lha <luisealvarezb@gmail.com> - 2015-09-18 07:54 -0700

csiph-web