Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Saturday 18 April 2015

Sandi Metz suspicion of nil (pbox2d example)

Late last year Sandi Metz blogged about Suspicions of nil, more recently she presented Nothing is Something at Bath ruby, and I just watched the video at confreaks. The timing could not be much better I had just translated Dan Shiffmans MouseJoint sketch to run with ruby-processing, and the Spring class which has all these egregious checks for null (or nil in initial ruby version). I found that by using ruby duck-typing I could create a DummySpring class, that got rid of all those suspicious null checks!!!
The DummySpring class
# dummy_spring.rb by Martin Prout
# using duck-typing so class can stand in for Spring

# Using this class avoids test for nil
class DummySpring
  def initialize; end

  # If it exists we set its target to the mouse location
  def update(_x, _y); end

  def display; end

  # This is the key function where
  # we attach the spring to an x,y location
  # and the Box object's location
  def bind(x, y, box)
    spring = Spring.new
    spring.bind(x, y, box)
    spring
  end

  def destroy; end
end

The only slightly tricky thing was the sketch needs to know that DummyString bind returns an instance of Spring, but otherwise it all looks pretty cool. Would make a good example except that pbox2d confounds things (we have two worlds a jbox2d physics world and a processing sketch world, and we track both).

No comments:

Post a Comment

Followers

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2