Alternative Way to Refine A Class

This Jackbox feature showcases an alternative way to refine classes,
that also illustrates some additional uses of our modular
closures/injectors. For this to happen, we rely once again on our trusty
method #lets. Take a look at this example code:

  # Injector declaration

  StringExtensions = injector :StringExtensions do
    def to_s
       super + '++++'
     end
  end


  # Jackbox Re-Classing

  lets String do
       include StringExtensions
  end
  str = String('boo')

  assert(
    str.to_s == 'boo++++'
  )

  assert(
    String.new('bar).to_s == "bar"
  )

For more details please visit:
http://blog.jackbox.us/2015/09/an-alternative-way-to-refine-class.html

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)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs