All atomic-powered posts filed in “Languages”:
Testing C# code that is run as the result of a event being fired
Or, How to test your Presenter classes
A couple of colleagues and I recently finished up a project for a client that involved a lot of C# code. Our unit testing tools of choice were NUnit and Rhino Mocks. The NUnit choice was a pretty easy one (although there are other platforms out there), but we spent a little more time choosing a mocking library. Our first choice was NMock, primarily because we had experience using it on previous projects and we knew it could get the job done. Before too long, though, we switched to using Rhino Mocks. The primary reason for the change (if I am remembering correctly) was because of its superior event handling capabilities, and we grew to prefer its explicit use of the record-playback-verify mocking model. Rhino Mocks was one of the first libraries to directly support event registration and event raising by mocks (at least, it was the first we had used). This was a big advantage over having to add a SubscribeEvent() method to our view and model interfaces and having to use syntactically obscure paradigms to capture and fire the event raisers. With Rhino Mocks we could add public events directly to our interfaces and (fairly) explicitly capture the event raisers. Read the rest of this entryRuby and Unicode Win32 MessageBoxes
Have you ever needed to display Unicode characters in a Win32 MessageBox from a Ruby script? My pair and I needed to do just that and so I thought I would share what we found.
There are a number of ways to access Win32 calls from a Ruby script. The code we were working with did the following:
1 2 3 4 5 6 7 8 9 |
require 'dl' def show_message_box(message, title) mb_ok = 0 mb_iconexclamation = 48 user32 = DL.dlopen("user32") message_box = user32['MessageBoxA', 'ILSSI'] message_box.call(0, message, title, mb_ok | mb_iconexclamation) end |
That works well until you need to display Unicode characters in the MessageBox. It turns out the MessageBoxA version of the function is for ASCII characters. There is another version of the API call, MessageBoxW, that can handle Unicode, or wide characters. So the issue becomes converting your Ruby string into a wide string so it can be passed to MessageBoxW. The MultiByteToWideChar Win32 call can do this for you. And the windows-pr gem (from win32utils) adds a nice ruby wrapper around the function.
gem install windows-pr |
1 2 3 4 5 |
require 'windows/unicode' include Windows::Unicode $KCODE='UTF8' str = multi_to_wide("This is a test") |
This seemed to work quite well for the most part. However, from time to time we would see garbage text showing up at the end of our messages. It could easily be reproduced if the message was very short.

Having done enough C/C++ coding to recognize a string that was not being null terminated, we experimented with adding null characters to the end of the string. It turns out a wide null terminator (”\0\0”) is needed. The following code will properly display Unicode characters in a Win32 MessageBox:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
require 'dl' require 'windows/unicode' include Windows::Unicode $KCODE='UTF8' def win32_wide(text) multi_to_wide(text) + "\0\0" end def show_message_box(message, title) mb_ok = 0 mb_iconexclamation = 48 user32 = DL.dlopen("user32") message_box = user32['MessageBoxW', 'ILSSI'] message_box.call(0, win32_wide(message), win32_wide(title), mb_ok | mb_iconexclamation) end show_message_box "MessageBox displayed from Ρουμπίνι", "¡Alert!" |
Roll Your Own respond_to
While refactoring some ruby code the other day I found myself wanting respond_to-like functionality. Specifically, I was calling a function that would have one of several possible outcomes, and I wanted to handle each in a clean way. Specifically, I wanted syntax like this:
1 2 3 4 5 6 7 8 |
zebra array do |row| row.even do |element| puts "even #{element}" end row.odd do |element| puts "odd #{element}" end end |
I put together a bit of code for doing this, called Multiblock. You could write zebra, with a Multiblock, like so:
1 2 3 4 5 6 |
def zebra(list) list.each_with_index do |element, index| odd_or_even = [:even, &odd][index % 2] yield Multiblock[odd_or_even, element] end end |
Here’s the source code for Multiblock:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
class Multiblock def self.[](*args) new *args end def initialize(*args) _expect *args unless args.empty? end def [](*args) _expect *args self end def method_missing(name, *rest) if !@matched @matched = [@waiting_for, :else].include? name if @waiting_for == name @result = yield *@args elsif :else == name @result = yield @waiting_for, *@args end end @result end private def _expect(waiting_for, *args) @waiting_for = waiting_for.to_sym @args = args @result = nil @matched = false end end |
Some useful selenium helpers
Wouldn’t it be nice if you could evaluate arbitrary javascript in the context of your Rails application’s window when testing it with Selenium? Well, you already can. What Selenium doesn’t do for you, however, is automatically serialize the result of your computation to JSON, then deserialize that JSON into a convenient ruby object. What I want to do is stuff like this:
1 2 3 |
# get the center of the page's google map lat, lng = get_json "[c.lat(), c.lng()]", :c => "googleMap.getCenter()" |
or
1 2 |
positions = get_json "{foo: $('foo').offsetLeft, bar: $('bar').offsetLeft}" assert positions['foo'] < positions['bar'], "bar was too far to the right" |
Here’s the definition of get_json:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# evaluate arbitrary javascript in the context of your page. def eval_js(code) get_eval <<-JS selenium.browserbot.getCurrentWindow().eval("#{ code.gsub('"', '\\\\"').gsub("\\n"," ") }") JS end def get_json(code, objects={}) entries = objects.entries ActiveSupport::JSON.decode( eval_js(" Object.toJSON( (function(#{entries.map (&:first).join(', ')}){ return #{code}; })(#{entries.map(&:last).join(', ')}) ) ") ) end |
Desktop Application Development in JRuby
Is JRuby a realistic candidate for authoring complex desktop applications?
Yes.
Last spring Karlin Fox and I became involved with a project that aimed to rewrite an old DOS app as a modern desktop app. Once Java was selected as our platform we immediately began to consider if JRuby could play a role in the project. We discussed several levels of JRuby usage. We had applied JRuby in the past for testing and various tool-smithing tasks, but we wanted to see JRuby play a larger role. The decision was made to write as much of the application as possible in Ruby.
We are now in the 22nd week of the project and there have been no regrets with our decision to use JRuby. It continues to excite me that I get to use my favorite programming language to test and create an attractive desktop application. Micah Alles joined the project in the 10th week increasing the team to three members. The code is now being exercised by 793 RSpec examples at the unit level and 73 integration examples that exercise the app just below the GUI. The application has reached a size of 187 classes which contribute to 7,890 lines of code.
The application is a simulation that shows a two dimensional topological view of connected nodes that the user gets to interact with. Users can load different topologies into the application. Data is gathered while the simulation runs and the user has the ability to view various reports about their performance.
We are using the Batik SVG Toolkit to render the topology. The rendered SVG is interactive. Clicking on components brings up swing dialogs. Using SVG gave us the ability to easily integrate artwork created by the design team.
Using Swing components through JRuby has been much easier than with straight Java. We have built several complicated widgets using complex components like JTable. For layout purposes we have used Cheri::Swing, Profligacy, translated output from the Netbeans GUI designer, and rolled some views by hand. Our only setbacks have been the slow progress of Java integration features in JRuby and the lack of a comprehensive Swing layout manager.
We are bundling all of the application’s Ruby code, Ruby and Java dependencies, and JRuby itself into a single executable jar which we deliver weekly at the end of each iteration. Our target OS is Windows, but we all develop on OS X and Linux as well.
We should be able to provide some screen shots by springtime when the application is officially released, and will post anything noteworthy during the rest of our development effort. Please share any JRuby success stories you have with us and be sure to post them on the JRuby wiki. Thank you JRuby team!
RubyConf 2007: Enhancing Embedded Development with Ruby
I’ve just given this presentation at Rubyconf 2007. And now you can enjoy it too:
Keynote file: Enhancing Embedded Keynote
PDF version: Enhancing Embedded PDF
Video: Full Video from Confreaks
Ruby String#split
Taking a string and splitting it with a delimiter is a very common task in Ruby. The official documentation states that String#splitdivides str into substrings based on a delimiter, returning an array of these substrings.
The delimiter itself can be a string or regular expression:
1 2 3 4 5 6 7 |
#string delimiter "hello".split('') #=> ["h", "e", "l", "l", "o"] "hello".split('ll') #=> ["he", "o"] # regular expression delimiter "hello".split(//) #=> ["h", "e", "l", "l", "o"] "hello".split(/l+/) #=> ["he", "o"] |
String#split takes an optional second parameter representing a limit. From the String#split documentation:
If the limit parameter is omitted, trailing null fields are suppressed.
If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array).
If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.
Here are some examples of how the limit parameter works:
1 2 3 4 5 6 7 8 9 |
# omitting the limit "1234 1234".split('4') # =>["123", " 123"] # positive limit "1234 1234".split('4', 1) # => ["1234 1234"] "1234 1234".split('4', 2) # => ["123", " 1234"] # negative limit<code> "1234 1234".split('4', -1) # => ["123", " 123", ""] |
These examples have been short and simple and in my experience the common usages of String#split will be. When you start to go beyond the short and simple you will find some behavioral oddities with String#split and it will always be with regular expression delimiters.
Read the rest of this entryD Programming Language for Systems & Embedded Programming
Greg and I are working at X-Rite these days on an extended assignment. We’re part of a team developing a new color measurement device. It’s a complicated embedded system and the first large-scale implementation of our Agile and TDD approaches to embedded system development (incidentally, thanks, X-Rite, for your faith in us). One of our team members, Mark, has some familiarity with the D programming language. I’ve heard of it. It’s been in development for quite some time. Version 1.0 was just released in January of 2007. Because of Mark I just checked it out. It’s nice.
Read the rest of this entry