Mark Needham

Thoughts on Software Development

Archive for the ‘Ruby’ tag

rspec – Invalid character '\240′ in expression

with one comment

We have been using rspec on my project for the unit testing of our Ruby code and while running one of the specs last week I ended up getting this somewhat en-cryptic error message:

Invalid character '\240' in expression
...

After convincing myself that this error wasn't actually possible it turned out that I had somehow entered an 'invisible to TextMate' character after one of the method definitions – on the editor it just looked like a space.

I'm not sure exactly what the character was but deleting it got rid of the error and got my test/spec running again.

Written by Mark Needham

October 6th, 2008 at 8:48 pm

Posted in Ruby

Tagged with ,

Calling shell script from ruby script

with one comment

Damana and I previously posted about our experiences with different Ruby LDAP solutions.

Having settled on Ruby-LDAP (although having read Ola and Steven's comments we will now look at ruby-net-ldap) we then needed to put together the setup, installation and teardown into a ruby script file.

A quick bit of Googling revealed that we could use the Kernel.exec method to do this.

For example, you could put the following in a ruby script file and it would execute and show you the current directory listing:

exec "ls"

The problem with using Kernel.exec, which we became aware of after reading Jay's post, is that we lose control of the current process – i.e. the script will exit after running 'exec' and won't process any other commands that follow it in the file.

Luckily for us there is another method called Kernel.system which allows us to execute a command in a sub shell, and therefore continue processing other commands that follow it.

We were able to use this method for making calls to the make script to install Ruby-LDAP:

@extconf = "ruby extconf.rb"
system @extconf
system "make"
system "make install"

There is one more option we can use if we need to collect the results called %x[...]. We didn't need to collect the results so we have gone with 'Kernel.system' for the time being.

Jay covers the options in more detail on his post for those that need more information than I have presented.

Written by Mark Needham

October 6th, 2008 at 8:12 pm

Posted in Ruby

Tagged with , ,

Ruby: Ignore header line when parsing CSV file

with 4 comments

As my Ruby journey continues one of the things I wanted to do today was parse a CSV file.

This article proved to be very useful for teaching the basics but it didn't say how to ignore the header line that the CSV file contained.

The CSV file I was parsing was similar to this:

name, surname, location
Mark, Needham, Sydney
David, Smith, London

I wanted to get the names of people originally to use them in my code. This was the first attempt:

1
2
3
4
5
6
7
8
9
10
require 'csv'
 
def parse_csv_file_for_names(path_to_csv)
  names = []  
  csv_contents = CSV.read(path_to_csv)
  csv_contents.each do |row|
    names << row[0]
  end
  return names
end

I then printed out the names to see what was going on:

1
2
3
4
names = parse_csv_file_for_names( "csv_file.csv" )
names.each do |name|
  puts name
end

This is what was printed:

name
Mark
David

It turns out that the 'shift' method is what I was looking for to help me ignore the first line of the file. The new and improved method now looks like this:

1
2
3
4
5
6
7
8
9
10
11
require 'csv'
 
def parse_csv_file_for_names(path_to_csv)
  names = []  
  csv_contents = CSV.read(path_to_csv)
  csv_contents.shift
  csv_contents.each do |row|
    names << row[0]
  end
  return names
end

Not a particularly complicated thing to do in the end although I had been expecting to find a method on CSV that would allow me to ignore the header line automatically. As far as I could tell there isn't one!

Written by Mark Needham

October 4th, 2008 at 1:32 am

Posted in Ruby

Tagged with ,

Ruby: Unzipping a file using rubyzip

with 6 comments

In the world of Ruby I've been working on a script which needs to unzip a file and then run an installer which is only available after unpacking it.

We've been using the rubyzip gem to do so but so far it hasn't felt intuitive to me coming from the Java/C# world.

ZipFile is the class we need to use and at first glance I had thought that it would be possible to just pass the zip file name to the 'extract' method and have it do all the work for me!

Turns out you actually need to open the zip file and then create the directory location for each file in the zip before extracting them all individually.

We eventually ended up with this little method:

1
2
3
4
5
6
7
8
9
10
11
12
require 'rubygems'
require 'zip/zip'
 
def unzip_file (file, destination)
  Zip::ZipFile.open(file) { |zip_file|
   zip_file.each { |f|
     f_path=File.join(destination, f.name)
     FileUtils.mkdir_p(File.dirname(f_path))
     zip_file.extract(f, f_path) unless File.exist?(f_path)
   }
  }
end

Which we can then call with the zip file and the destination where we want to unzip the file.

1
unzip_file("my.zip", "marks_zip")

Is there a better way to do this? It feels a bit clunky to me at the moment.

Written by Mark Needham

October 2nd, 2008 at 12:04 am

Posted in Ruby

Tagged with ,

Alt.NET Sydney User Group Meeting #1

with 3 comments

James Crisp and Richard Banks arranged the first Alt.NET Sydney User Group meeting held on Tuesday night at the ThoughtWorks office.

The first thing to say is thanks to James and Richard for getting this setup so quickly – it was less than a month ago that Richard suggested the idea of creating a group on the Alt.NET mailing list.

Richard and James have already written summaries of what went on but I thought I'd give some of my thoughts as well.

The meeting was split into three parts with a retrospective on proceedings at the end:

.NET News

Richard opened the meeting by talking about some of the latest news in the .NET community in the last month or so.

I thought this worked very well and helped to get some discussion going very early on. One of my comments from the London Alt.NET Conference was that very few people seemed to get involved – that certainly wasn't the case last night and there was a very collaborative feel about the whole event.

The first news was that the much talked about jQuery is going to ship with ASP.NET MVC and Visual Studio and that Microsoft intend to provide Product Support Services for it and contribute any changes they make to it back into the community. It was suggested that this is a bit strange as jQuery is effectively a competitor to Silverlight – Microsoft's plugin for developing rich applications for the web. Apparently Nokia are also intending to get involved.

Another thing which I hadn't heard about was the DevSta coding competition which was mentioned at Tech Ed earlier in the year. I haven't read exactly what the competition is all about but you get 200 hours and 8 minutes to prove your skills with Visual Studio 2008. The challenge is here for those that are interested.

Richard also pointed out some open source projects which I hadn't come across, notably CloneDetectiveVS – a duplicate code finder plugin for Visual Studio – and SnippetDesigner – another plugin to create code snippets. Not sure how different this would be to Resharper's code templates but it's another option.

A new language which runs on the CLR called Cobra was mentioned. It has support for contracts and testing so it could be a contender – probably needs someone high profile to run with it for that to happen I would imagine.

gocosmos was also discussed – an operating system project implemented completely in CIL compliant languages.

The WebDirections conference was also mentioned – the Microsoft Surface seemed to be the most interesting thing to come out of this.

Ruby and Rails From a .NET Perspective

James opened the second half of the evening with a talk about using Ruby in the world of .NET.

He opened with a brief history of the Ruby language going through some of the ideas that Ruby brings to the table – principle of least surprise being the most intriguing one to me – before covering some of the Ruby compilers currently available – MRI, YARV JRuby and IronRuby. The last one was the focus for the talk – being a .NET implementation of the Ruby language.

James went through some demos using the Interactive IronRuby Console to start with but later showing how to create a simple application using Rails.

There was an interesting discussion around testing – James pointed out that the Ruby/Rails world is much more test focused than the .NET one and unit testing is available right out the box.

I haven't worked with Ruby enough to know if everyone in the Ruby world unit tests but as a general feeling I would say this is probably accurate.

RSpec was covered briefly as an alternative to the Test::Unit framework that comes baked in with Rails. I haven't played around with it before but as I'm working a bit in the world of Ruby at the moment it is something that I hope to use in the near future.

Finally build and deployment tools from the Ruby world such as Capistrano and Rake were mentioned. I can see the latter having some influence but as the former is meant for Unix I can't see it being heavily used in the .NET world.

Rhino Mocks

Richard closed the evening with a presentation on Rhino Mocks.

I went into this presentation with the belief that Moq was the way to go when it comes to .NET mocking frameworks.

The Arrange Act Assert or Mockito approach to mocking is one which makes it much easier to do and leads to far less clutter in tests.

I thought this was only possible in Moq and that Rhino Mocks encourage the Record/Replay approach. As Richard pointed out, this is no longer the case.

Richard gave a demonstration on several of the ways that you can use Rhino Mocks in your testing efforts – covering simple interaction testing, event testing and several other clever techniques that Rhino Mocks allows.

An interesting statement was made that 'Mocking = Genuine Unit Testing', a statement that I tend to agree with. Several people mentioned that they now realised their unit tests were actually functional tests – this is a problem which mocking can help to reduce.

Overall

Overall it was again interesting to meet up with the .NET crowd and hear the different ways that people are doing – I was impressed with the turn out given the short notice – there were over 30 people in attendance.

The next meeting is on 28th October 2008, ThoughtWorks Sydney Office, 51 Pitt Street again.

Written by Mark Needham

October 1st, 2008 at 10:09 pm

Posted in .NET

Tagged with , , , ,

Ruby: Parameterising with ActiveResource

without comments

We've been using Ruby/Rails on my current project to create a RESTful web service. One of the problems we wanted to solve was making the data queried by this web service configurable from our build.

We started off with the following bit of code (which makes use of the recently added ActiveResource class):

1
2
3
class MyClass < ActiveResource::Base
  self.site = "http://localhost:3000/"
end

And then called this class as follows:

1
MyClass.create(:param => "param-value")

This worked fine for us until we wanted to parameterise the 'site' value so that we could set it to different values depending which build we were running (dev/ci/qa). We tried all the obvious ways – overriding the constructor and passing in the site, trying to set the site by calling MyClass.site but none of them did what we wanted. We eventually ended up creating a new method to create an instance of the class with our configurable site:

1
2
3
4
5
6
7
8
class MyClass < ActiveResource::Base

def instance(site, args)
  self.site = site
  new(args) unless args.nil?
end

end

We then call the code like this:

1
2
my_class = MyClass.instance("http://localhost:3000", :param => "param-value")
my_class.save

It seems like a bit of a hack but it got it working!

Out of interest it has taken me ages to try and find a way to put the Ruby code on here in a readable format. I tried to use the TextMate exporter but that wasn't giving me any love. I eventually ended up using Spotlight, a neat little tool written by Tyler Jennings. I found it from Jake Scruggs blog post.

Written by Mark Needham

August 8th, 2008 at 10:16 pm

Posted in Ruby

Tagged with , , ,

Watching a master at work

without comments

I've always found it fascinating watching people who really excel in their field going about business, be it footballers, tennis players, actors, whoever.

This week at TWU I've been playing around with some Ruby on Rails as I mentioned in the previous post, and yesterday I had the opportunity to watch one of the leading figures in the Ruby on Rails field at work. Take a bow Obie Fernandez, who gave several of the TWU attendees a demonstration of how to develop applications using Ruby on Rails. It was actually bordering on the severely impressive watching the speed at which he thought through concepts and then transformed them into code.

I also realised that the way I'd been using the language previously had been dubious at best. I hadn't realised that you can take care of database creation without using MySQL Administrator, nor had I realised quite how 'clever' Ruby on Rails is at mapping database tables to models created in the application.

It was almost painful watching how simple it is to do arduous tasks, such as creating textboxes and drop down boxes, in Ruby on Rails and it almost made me want to weep as I recalled the many hours I've spend using PHP and C# tweaking interaction between code and stored procedures/queries.

So +1 for Ruby on Rails and I certainly hope to improve my ability with it over the next few weeks.

Written by Mark

September 2nd, 2006 at 1:01 am

Posted in Ruby

Tagged with , , ,

First thoughts on Ruby…

without comments

I've heard a lot about Ruby on Rails over the last couple of years but I'd never really been intrigued to get it set up on my machine and 'have a play' with it so to speak.

It turned out to be a relatively painless process and after following the instructions on the official site I had it all setup within about half an hour which was a record for me for getting a development environment setup. With a bit of help from the Pragmatic Programmers Guide to Ruby I managed to get some basic pages setup. The design of the URLs and the separation of the code is actually fairly intuitive. Ruby on Rails uses the MVC (Model – View – Controller) Architecture/Design Pattern very strictly and the code for each of these is written in a separate file.

One aspect of this that made sense to me as a PHP programmer was the way that the URLs in Ruby on Rails are constructed in a "/[controller_name]/[action]" format. I also like the fact that everything in Ruby on Rails is an object, even such things as integers and strings. It takes a bit of getting used to but after using it for a bit it seems counter intuitive to do it any other way.

I don't think I'm about to become an advocate for the use of Ruby on Rails for every development project I work on – I'm still a big fan of C# and the .NET platform and I find it unlikely that I'll change my mind in the near future but we shall see!

Written by Mark

August 29th, 2006 at 8:01 pm

Posted in Ruby

Tagged with ,