Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Tuesday, December 1, 2009

Write Implementation and Spec on the Same File

-- For http://atnd.org/events/2351 day 1

Sometimes it would be preferable to write the implementation and the specific on the same single file because of the reasons including ease of maintenance and ease of distribution. The following snippet will be helpful for the purpose.

#!/usr/bin/env ruby

{implementation}

case $0
when __FILE__
  {command line interface of the implementation}
when /spec[^/]*$/
  {spec of the implementation}
end

For example, assuming a.rb is that you've written with using the template,

  • ruby a.rb runs {implementation} and {command line interface of the implementation}
  • ./a.rb runs {implementation} and {command line interface of the implementation}
  • spec a.rb runs {implementation} and {spec of the implementation} with RSpec
  • require 'a' in other scripts runs only {implementation}.

No comments:

Post a Comment

Followers