Programming

RSpec matcher helper

| |

I've finally written more than one RSpec matcher. Creating a matcher essentially involves defining a class and a method that creates an instance of that class. Rather redundant, resulting in my RSpec matcher helper:

def defmatcher(name, &code)
  klass = Class.new
  klass.module_eval(&code)
  
  Object.send :define_method, name.to_s do |*args|
    klass.new(*args)
  end
end

That little method, defmatcher, creates the class and method for you. It saves some typing. An example can be found in the full source file, available here.

Update (2008/06/28): RSpec was having trouble keeping this all in one file. I created a project at GitHub to host this for the time being: http://github.com/sneakin/spec_matcher_helper/

Experiments with Erlang

| | |

Earlier today I setup an instance of HgWeb to host some old and new code bases of mine. Two of the repositories may interest those learning or looking to learn Erlang. Both repositories contain a simple project that doesn't amount to much of anything at the moment, though they could prove useful for some code reading/banging.

The two repositories are:

  • Station: This is a super basic, simple HTTP server framework. It can currently parse an HTTP request which gets dispatched to a station behavior that you can define. The station behavior contains a function that gets called on each valid request and returns a response which is sent back to the requestor. Proper query string and form handling still needs to be done along with dispatching to different modules based on the requested path.
  • mod_rest: This is an ejabberd module that adds an HTTP handler that allows HTTP clients to literally post arbitrary message stanzas to ejabberd. Those stanzas then get shoved through ejabberd's router just like any other stanza. My original use for this was to allow a Rails app to send messages through ejabberd without needing to be a full XMPP client.

You will need to install Mercurial to get the code onto your machine. It's the next best thing to git.

Dot Plots: A Coder's Towel

|

I just slapped together a dot plotter after scanning through Object-Oriented Reengineering Patterns. That book describes the use of dot plots to detect duplicated code. While it's a bit like reading tea leaves, it is a good detector as the following two plots of dotplotter.rb against itself show with the huge run down the middle:

Dot Plot of dotplotter.rb against itself in Ruby mode (-r) Dot Plot of dotplotter.rb against itself in Line mode (-r)

The first is dotplotter.rb running with the "-r" option which compares tokens to tokens thus making each row/column a token such as "def". The second, smaller one is in line mode, "-l", which compares lines with lines. That makes each row/column an actual line in the source file.

The huge diagonal line through the middle indicates a huge run of duplicated code. That's because it's the same file against itself. Now if these were separate files, then the runs would hopefully not exist since any such run indicates duplication.

The dot plot script can be found at the following site. It requires RMagick and ParseTree to work: http://nolan.eakins.net/code/dotplotter.rb

eXtreme Programming Gone Wrong

|

This is what eXtreme Programming looks like when it goes wrong with way too many index cards or in this case Post-It notes:

XP Gone Wrong

Intellectual Property and oDesk

| |

I followed the link TechCrunch posted to oDesk since I need some work. I found some job posting that I found interesting and proceeded to sign up. Low and behold the first service agreement I read just wasn't palatable. From my understanding of their Professional Services Agreement, any pre-existing intellectual property that is incorporated into a project can essentially be used for whatever purposes oDesk wants.

I wouldn't have an issue if this granted a license to the company that has requested the work, but it is oDesk—the site that connects professionals with those that need work done. I have a body of code that's gradually getting larger that allows me to be more productive, and I like to set my own terms on its use. Sorry, I won't grant an unlimited license to it to a company whose unstated business is to hoarde IP.

Super Coder

Mimír just told me why Windows Vista will be late. One of the reasons is that the developers are only writing 5000 lines of code per year. This is only slightly less than the national average of 6200 lines of code.

That's just shocking!

My latest project, a web page to collect donations for a full page ad, took me about a month and a half to complete. It was done with RoR so it comes with the ability to tally up lines of code. In total I wrote 3062 lines of code. That includes actual application code, 2229, and test code, 833.

I have no idea if my rate is typical, below average, or above. What I know now says that another two months of coding will cause me to cross the national lines of code average. And keeping up the rate for that last project, in one year I will have surpassed the national average by 18,292 lines of code (3062 / 1.5 * 12 - 6200).

OSS and Agility

Poking around some wee corners of the net I found my way to Open Source as Agile Process (note: relying on GOOG since C2's wiki is down). It has a list of open source principles that meshed with agile software development.

One stood out though: be open to the point of promiscuity.

Hit By a Train

|

I'm actually trying to produce something with Ruby on Rails, and I finally got hit by the train. Here's the problem that makes no sense at all. I have a view that does the following:

<%= render :partial => 'role', :collection => @roles %>

@roles is a class attribute that's an array of roles which gets iterated over. This is where things get foobarred. In the partial I get a variable called role which is good, but I want to render a text field in this partial. Rails provides me with text_field. Good again because I can just enter the following to print the role's name:

<%= text_field "role", "name" %>

But wait! text_field will only work with class attributes for some dumb reason. Yes, that means it'll call @role.name to get the name, not role.name. If I wanted @role, I would have used @role in my call to text_field.

I can not figure out why this could have been a good idea. Now I'm stuck contemplating whether I should hack up my own text_field that works logically or not.

Long Live Static Typing!

I just read an article that mentioned dynamic and statically typed languages, and I also just looked up Ruby's yield statement. One of the examples on the page I found was this:

class SongList
  def [](key)
    if key.kind_of?(Integer)
      @songs[key]
    else
      # ...
    end
  end
end

The problem I have is with the if key.kind_of?(Integer). I've been toying with Lisp some, and it reintroduces static typing (think C/C++ function/method arguments). So the above could be simplified a lot, especially if a method needed to be specialized for a ton of types. This could be done by specifying an argument's type. The following would work perfect, and could allow some optimizations to be made too:

class SongList
  def [](Integer key)
    @songs[key]
  end

  def [](key)
    # ...
  end
end

Ruby Style Continuations In Lisp

|

A few days ago I found out Ruby supported continuations. I started playing with them in an experiment to be detailed later. One of the things Ruby has over Lisp is an understandable syntax for them. In Lisp all I had was Paul Graham's continuation code from his Lisp book:

(setq *cont* #'identity)

(defmacro =lambda (params &body body)
  `#'(lambda (*cont* ,@params) ,@body))

(defmacro =defun (name params &body body)
  (let ((f (intern (concatenate 'string
				"=" (symbol-name name)))))
    `(progn
      (defmacro ,name ,params
	`(,',f *cont* ,,@params))
      (defun ,f (*cont* ,@params) ,@body))))

(defmacro =bind (params expr &body body)
  `(let ((*cont* #'(lambda ,params ,@body))) ,expr))

(defmacro =values (&rest retvals)
  `(funcall *cont* ,@retvals))

(defmacro =funcall (fn &rest args)
  `(funcall ,fn *cont* ,@args))

(defmacro =apply (fn &rest args)
  `(apply ,fn *cont* ,@args))

PG also provided some examples using that. One of them was a depth first traversal. It creates the continuation when it pushes a lambda. The syntax basically offers no help in understanding how to use it as you can see:

(setq *saved* nil)

(=defun dft-node (tree)
  (cond ((null tree) (dft-restart))
	((atom tree) (=values tree))
	(t (push #'(lambda () (dft-node (cdr tree)))
		 *saved*)
	   (dft-node (car tree)))))

(=defun dft-restart ()
  (if *saved*
      (funcall (pop *saved*))
      (=values 'done)))

(=defun dft2 (tree)
  (setq *saved* nil)
  (=bind (node) (dft-node tree)
    (cond ((eq node 'done) (=values nil))
	  (t (princ node)
	     (dft-restart)))))

Even with that example, I still couldn't wrap my head around it until I started playing with Ruby's. Ruby has a callcc keyword that creates a continuation. It's syntax is basically:

callcc do |cc|
   # Do some stuff
end
# Do some other stuff when we call 'cc' above

That syntax makes it pretty easy to understand how to use them which is all that matters. PG's example code offered nothing in that direction, so I recreated PG's DFT example in Ruby and got the following:

$conts = Array.new

def dft_restart()
  if $conts.length > 0
    $conts.pop.call
    return nil
  end
end

def dft_node(tree)
  if tree == nil
    dft_restart
  elsif tree.class != Array
    return tree
  else
    callcc do |cc|
      $conts.push cc
      return dft_node(tree[0])
    end
    return dft_node(tree[1, tree.length])
  end
end    

def dft2 tree
  $conts = Array.new
  node = dft_node tree
  if node != nil
    puts node
    dft_restart
  end
end
Ruby's callcc helped me understand exactly what was going on. So I started messing around and created a macro that creates Ruby's callcc in Lisp. This is the macro:

;; Ruby style syntax
(defun search-replace (list key value)
  "Replace all instances of KEY found in LIST with VALUE."
  (cond ((null list) nil)
	((symbolp list) (if (eq list key) value list))
	((atom list) list)
	(t (cons (search-replace (car list) key value)
		 (search-replace (cdr list) key value)))))

(defmacro callcc (inner &body body)
  (let ((var-name (first inner))
	(var-exp `#'(lambda () ,@body)))
    `(progn ,@(search-replace (cdr inner) var-name var-exp))))

The syntax for that is essentially like Ruby's:

(callcc (cc do some stuff)
   Do some more stuff when we call 'cc')

The cc variable name can be changed to whatever, and it represents the continuation that you can save to call later. So back in Lisp PG's DFT-NODE then becomes:

(=defun dft-node (tree)
  (cond ((null tree) (dft-restart))
	((atom tree) (=values tree))
	(t (callcc (cc
		    (push cc *saved*)
		    (dft-node (car tree)))
 	      (dft-node (cdr tree))))))

To me anyway that makes more sense because the voodoo isn't up front. It's tucked into the callcc. To you innocent bystanders, it probably still makes no sense, but now you have some code to play with.

Syndicate content

Ad's by Google