Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Wednesday, September 09, 2009

Fun With Metaprogramming: hash_initializer()

Earlier this week I was doing a code review for a candidate for ThoughtWorks. One of the bits I ran across was an object constructor that looked something like this:

class MyClass
def initialize(name, price, is_cool, is_neato, is_rad)
@name = name
# et cetera
end
end

Not so bad, really, when you're looking right at the signature for the constructor. But when it's called from another file...

MyClass.new("bob", "1.00", true, false, true)
MyClass.new("fred", "2.00", false, true, true)
# et cetera

... the purpose of the first two parameters may be easy to infer, but the last three? Which order were those descriptors in anyway? To really be sure, one has to keep referring to the class definition. In my review, I opined that perhaps the constructor should take a single argument -- a hash with keys named after the objects instance variables and their corresponding values. Thusly:

class MyClass
def initialize(args)
args ||= {} # in case MyClass#new is called without any args
@name = args[:name] || ""
# et cetera
end
end

This frees things up a bit, and allows for parameters to be specified in any order, with reasonable defaults for any that might be left out. It also makes calls to the constructor a little more self-documenting.

But what would really be nice would be not having to write out this boilerplate code for everything that we want this kind of constructor for.

Enter metaprogramming, in the form of hash_initializer -- a nifty little class extension I found in Brian Guthrie's Awsymandias library (as used at my current ThoughtWorks gig). Behold:

1. module ClassExtension
2.
3. if !Class.respond_to?("hash_initializer")
4. def hash_initializer(*attribute_names, &block)
5. define_method(:initialize) do |*args|
6. data = args.first || {}
7. data.symbolize_keys!
8. attribute_names.each do |attribute_name|
9. instance_variable_set "@#{attribute_name}", data[attribute_name]
10. end
11. instance_eval &block if block
12. end
13. end
14. end
15.
16. end
17.
18. Class.send :include, ClassExtension

Lines 5 through 12 correspond pretty much to my second version of MyClass#initialize above. Line 6 does the same defensive guard against a nil first parameter. Lines 8 through 10 pull each attribute, create an instance variable with the same name, and set it to the desired value. The extra bits? Line 7 does something I should have done in my "improved" version -- it forces the keys of the params has to be symbols, avoiding the awkwardness of blowing up when a key is a String when it should be a symbol or vice versa. Line 11 allows for the execution of a block along with initialization, if you're into that sort of thing. And the rest just opens up the class Class and makes Class#hash_initializer available to all objects.

With Class thus extended, the boilerplate for MyClass becomes simply:

class MyClass
hash_initializer :name, :price, :is_cool, :is_neato, :is_rad
end

And instantiating a MyClass stays what you would expect:

MyClass.new :name => "bob", :price => "1.00" # et cetera.

I like it.

irb(main):001:0> Class#hash_initializer.is_neato?
=> true

Friday, August 15, 2008

Regarding Ruby, instance_of?, kind_of?, and ===

So I was reading through some Ruby source code tonight -- primarily because I haven't in a while, thanks to a busy stretch of Java work -- and I ran across an idiom that I found a little confusing at first. The Ruby source code belongs to Why the Lucky Stiff's Shoes project, "a very informal graphics and windowing toolkit" (according to the official website).

One of the first files I looked at, lib/shoes.rb, opens right up with this interesting bit of interestingness:
class Range 
def rand
conv = (Integer === self.end && Integer === self.begin
? :to_i
: :to_f)
((Kernel.rand * (self.end - self.begin))
+ self.begin).send(conv)
end
end
Okay. So we're defining a rand() method on the built-in Ruby class Range, which will return a random value from within the begin and end values of the Range. Neato. And apparently the use of conv is meant to produce a result of a float or an integer, depending on the nature of the endpoints of the Range. Again: neato. But I hadn't seen the use of the === operator in this context before.

The docs and the Pickaxe book are a little obtuse on this, so I did some irb spelunking:
>> r = (1..27)
=> 1..27
>> r.class
=> Range
>> r.begin
=> 1
>> r.begin.instance_of? Integer
=> false
>> r.begin.class
=> Fixnum
>> r.begin.kind_of? Fixnum
=> true
>> r.begin.kind_of? Integer
=> true
Hmm. So instance_of() doesn't mean quite the same in Ruby as, say, the instanceof operator in Java does. (That, or Fixnum doesn't truly inherit from Integer in Ruby.)

Also, as it turns out:
>> Fixnum === r.begin
=> true
>> Integer === r.begin
=> true
So it would seem that the [class] === [value] syntax is syntactic sugar for [value].kind_of? [class]

It's the bit about:
>> r.begin.instance_of? Integer
=> false
that surprised me most, being the pathetic Java programmer that I am. And being that (according to the documentation for Integer on ruby-doc.org):
Integer is the basis for the two concrete classes that hold 
whole numbers, Bignum and Fixnum.
Apparently "is the basis for" != "is a superclass of".

Or is that "!==="...?

Friday, June 20, 2008

HOWTO: Display a Custom Boot Message for Your VMWare Appliance

So I'm building a VMWare appliance for Stratavia's Data Palette data center automation application, and I want it to be like all the other cool appliances that print out some system-specific configuration information (e.g., IP address) when it finishes booting. This is useful for when, say, your appliance runs a webapp via an HTTP server like Apache or Mongrel or Tomcat and you want to tell the user where to point his browser to see it in action.

I happen to be using the latest Ubuntu JEOS as the base OS for this appliance. As such, in order to hook in to the boot process, I am adding my changes to the /etc/rc.local file.

(Author's Note: The exact location and name of this file vary -- sometimes wildly -- between Linuxen. Some flavors use /etc/rc.d/rc.local. Gentoo uses /etc/conf.d/local.start. I paraphrase the immortal Daffy Duck in "The Scarlet Pumpernickel": "Fancy, thy name is Linux. To coin a phrase.")

Let's say you want your user to visit http://[whatever the IP address ends up being] following bootup to get the virtual ball rolling. But you don't know what that IP address will be when you bundle your appliance; it's going to be assigned dynamically at bootup (as it should be). No problema. Simply write a bit of script to scrape the IP address in your Linux flavor's version of rc.local, thusly (Note: The following bit of awesome is directly ripped off from the rc.local file of the MindTouch Deki Wiki appliance):
IP=`ifconfig eth0 | grep "inet addr" | awk -F ' ' '{print $2}' 
| awk -F ':' '{print $2}'`
If you're Richard Stallman or some other Unix guru and you already know what the heck all this does, you can just smile smugly and skip the next few paragraphs. For the rest of us:

ifconfig eth0 -- Run the system command ifconfig to print out the general networking information for this box (specifically, the first ethernet interface), and send ("pipe") its output to the grep command. The output for ifconfig eth0 will look something like this:

eth0      Link encap:Ethernet HWaddr 00:0c:29:2d:f7:73
inet addr:172.16.139.130 Bcast:172.16.139.255 Mask:255.255.255.0
inet6 addr: fe80::20c:29ff:fe2d:f773/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
[et cetera]


There are several more lines, but all we care about is the second line. The next command in the chain, grep "init addr", will filter out all the stuff we don't want, leaving us with just the second line. This is then fed to the first of two awk scripts.

The first awk script uses a field separator of "space" (-F ' '); this splits the inet addr line into its constituent "words", like "inet" and "addr:172.16.139.130". We just want the "addr:" word, so we print it as the output of the first awk script and send it to the second ({print $2}).

The second awk script splits its input using the colon as its field separator (-F ':') and prints the second word, which is -- tada! -- the IP address of the virtual machine. Whew.

The Rubyistas reading this blog (assuming I have any left) may have downloaded Ezra Zygmuntowicz's way-cool EngineYard Express VMWare image. Its bootup a little more involved, asking for input from the user on initial boot, and displaying several bits of information after every boot thereafter, such as the randomly-generated root and express user passwords. EY Express is running on Gentoo, so its startup hook is in /etc/conf.d/local.start.

EY being EY, they delegate all the heavy lifting to Ruby via some custom Ruby Gems: ey_reporter, config_system, and system. You have to do some serious filesystem spelunking to get there, but you can find the Ruby code that figures out the IP address (the equivalent of the bash script above) in
/usr/lib/ruby/gems/1.8
/gems/system-[version]/lib
/system/info/info.rb

Saturday, January 19, 2008

Installing Fox and FXRuby on Mac OS X Leopard (Intel)

I'm planning to start playing with some of the GUI toolkits available for Ruby, and I know there's a Pragmatic Programmers book (currently in beta) for FXRuby, so I thought I'd get the fixin's in place to be able to play with it. Unfortunately, the standard sudo gem install fxruby alone didn't get the job done for me. Even using MacPorts to install Fox first (sudo port install fox) let me down. Here's what (eventually) did work:

  • Download and Install Fox:

    • Download the source. I picked the current stable version from the "Downloads" section, "Linux/Unix" subsection.

    • Set the LDFLAGS environment variable as described in Lyle Johnson's (author of FXRuby and the book) very helpful post:
      export LDFLAGS="-dylib_file \
      /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib:\
      /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib"
      Note: There's a typo in Lyle's instructions that will trip you up if you just cut and paste from there; there should be a space between the "-dylib_file" and the first "/System/Library/...". And, in case you're cutting and pasting from here, there should be no space between the colon and the second "/System/Library/...".

    • cd to the expanded Fox source folder.

    • ./configure, with whatever options you would normally use. I didn't specify anything in particular.

    • sudo make install, again with your typical options. The vanilla command worked for me.



  • Install the FXRuby gem:

    • sudo env ARCHFLAGS="-arch i386" gem install fxruby

    • The extra bits about the ARCHFLAGS are a workaround for a problem in ld (and/or lipo) trying to build this gem for both PPC and Intel architectures. As you might guess, this will work for you only if you're on an Intel Mac.

    • From the Credit-Where-Credit-Is-Due department: I cribbed the "env ARCHFLAGS" trick from the most excellent Hivelogic website, specifically this post.



  • Write a cool GUI! (Haven't gotten that far on this item yet...)


Oh, and I'll be looking at Shoes too. No weird Unix/Linux project dependencies for that one, thank goodness. Just a regular .dmg to download and install. Nice.