May 27 2008

Design Patterns in Ruby - A Book Review

Published by Laurie Tagged as:, ,

In short: This book is good, go buy it.

In “Design Patterns in Ruby” Russ Olsen sets out to cover two distinct goals. First he introduces the idea of design patterns, and secondly he explores how the dynamic nature of Ruby allows patterns to be used with less effort than languages such as Java and C#.

The overview of design patterns is pretty comprehensive, though not a substitute for the GoF book, which is referenced regularly thoughout. Russ does a good job of covering the reasons why patterns are good, and the generaly coding philosophy that lead to them. It’s here that we get a first glimps of one of my favourite things about this book. Not only does Russ clearly present the original GoF ideas and concepts (with due credit given to them) but he add his own ideas, which I think are just as valid.

This is followed by a list of 16 patterns. 13 are from the GoF book, and 3 are new for Ruby. For each pattern he follows the same structure. First a bit of context to explain the general concept, then an reasonably in depth discussion of how to implement the pattern, with code examples. Its in this section that we really get to look at what Ruby adds. Next comes a look at how to use, and not to use the pattern, before finally looking at some examples of where the pattern is used in real world Ruby projects.

The descriptions of the patterns are accurate, and comprehensive, and certainly cover the information you would find in the GoF book, although not all patterns are covered, and the structure he follows is not quite strict enough for this to be a good quick reference book. It’s in the discussions of how Ruby (and dynamic programming in general) adapt the use of the patterns that this book really shines. Always the “tradational” use of the patterns is presented first, and then we get to see how we can adapt this. In some cases the language itself almost renders the pattern unnecessary, the command pattern springs to mind here, which can almost completly be replaced with Procs, lambdas or code blocks. I was very impressed at how Russ clearly explains the advantage of the tradational format too though.

The final 3 patterns (DSLs, Meta-Programming, and Convention over Configuration) were a very interesting addition. I don’t feel its really fair to call them patterns though. They more cover general techniques and are too general to accuratly be called patterns in my opinion. That’s not to say they are not useful, and an strong addition to anyone’s skill set.

The other aspect that shines though this book, is as an essay in teaching programmers used to static languages (Java etc) that Ruby is a fully fledged language, and capable of serious application work. Having been through this process I have finally decided I agree with this thesis, and in fact it was this book that finally helped me make up my mind. Pattern usage (and miss-usage) has long formed the basis of “enterprise” application development, and there is an underlying theme showing that Ruby not only supports patterns, but can make developing enterprise applications (with or without patterns) easier. However this is a double edged sword (isn’t everything) and I would have liked to have seen a bit more attention paid to how Ruby can make things harder, especially if it included some advice on how to mitigate the problems.

I also feel the need to point out that there are a too many errors in the book for my liking. Not big errors, but the occasional two line code example that contains the wrong code. If you have a general idea of what the section is about, it’s easy enough to see whats going on, but if your learning patterns and/or ruby for the first time from this book, it could cause a problem. Having said that I do have an early printing of the first version, and I am sure these issues will be picked up very fast.

Overall I was very impressed by this book, it covered a lot of things I already knew, fixed a few misconceptions I had, and taught me a few new things too.

No responses yet

May 05 2008

Best Practice work-flow with git

Published by Laurie Tagged as:, , , ,

Introduction

A quick look about on the web will bring you up-to speed on pretty much all you need to know about git. There are some great introduction’s to what it is, detailed manuals, and best of all an explanation of how it works aimed at people who understand computer science (and if you can’t follow that, you’re not going to earn much working as a programmer). However there is somethings missing from all these pages, and that’s some best practices on how you should actually use git. What work-flow should you use, and what best practices should you follow.

This is really important. The problems with subversion were not that some of its operation’s could be slow. Personally I never found myself staring at my screen, twiddling my thumbs, or going for a quick round of Mario Kart while waiting for subversion to finish something. The problem I always had with subversion was that my team and I were always treading on each others toes. We had a number of releases that were late because we were all committing code over each others’ work, and introducing unnecessary complexity.

However, there is a solution, and we found it. To fully understand it though, you need a good understanding of the problems that need solving.

The real problem with subversion

When I first came across continuous integration, I thought it was an absolutely great idea. If, as it often suggested, integrating work from different developers is hard, with the difficulty increasing roughly quadratically with time since the last integration, it make a huge amount of sense to integrate as often as you can. But I learned the hard way that it’s not true. At least not at the small scale. When someone else in my team is working on code, they, like all developers often go though a phase of sketching out their solution in code. This is normally pretty bad code from a production point of view. Their next step is to tidy this up, and make it into production quality code. It’s at this point that integration is good. Any fool can see trying to integrating my production code with a colleagues sketch code is bad. This is what happens with subversion though. Everything gets committed, otherwise you risk loosing your work if there is an issue (you won’t believe how often developer leave their laptops in bars). Branches are of course for exactly this reason, and I will talk about them later. For now lets just say I don’t know anyone using them successfully in subversion.

The problem with subversion then is that there is a tension, between trying to integrate your code with the rest of your team, and trying to get far enough down the route of maturing your code that you don’t create a bottle-neck. I experienced at least one case personally where one developer was doing a major chunk of refactoring, and it acted as a bottle-neck, preventing any bug fixes from other developers being committed and deployed. Subversion makes avoiding this too expensive.

The solution is branches, merging, and testing at each stage

Hopefully you knew that already, but does your team actually do it? This was always the answer I would give if asked how manage a code base, but no team I worked in ever managed it.

Why? Well quite simply, merging is hard. Subversion merges don’t work well with code that moves. If I move a chunk of code from one directory to another, subversion no longer tracks it well between branches. This is something I do a lot when refactoring code, and it breaks subversion.

On the other hand, because git expects merges, and moves, to be regular events it handles them very well. This is probably because under the hood it tracks the contents of your files rather your files, but at this level of understanding, all I care about is it works. I can create a branch, work on it, and merge, and apart from some annoying glitches between how editors handle whitespace, most things just work.

Git work-flow

This is the work-flow we chose (and if your skimming this article, this is the best bit to read)

First of all, we had a centrally hosted repository. I’m of the opinion that trying to run git with no repository being authoritative can work, but adds various complications, and pretty much no benefits. It might be cool, but that’s what the kids who give you cigarettes at school always said.

Then we had an authoritative branch on that repository. We all set our authoritative repository to be called “origin” and the branch was called master. Thus origin/master represented the state of the art production code. However, no-one, absolutely no-one was allowed to work on master. Most of the time everyone in the team (except the gatekeeper) did not even have master set up as a local branch.

Secondly, we had another branch on origin, called stable. Stable was always an ancestor of origin/master, but lagged behind a bit. Stable had various tags placed on it, which represented the actual public releases we made. More on this later.

Next each developer had as many branches as they wanted. Foremost though, each developer had a branch named after themselves. So I mostly worked in the ‘laurie’ branch, which was also on origin as origin/laurie. Along with this, each developer had a copy of the deployment platform on their workstation, and on on a staging server, in my case this was called laurie-stage. Each developer then works there. They write their tests, modify their code etc, making lots of commits along the way (the local nature of git commits makes regular small commits a very easy habit to get into, and it’s a very good one when you need to debug something that went wrong a while ago). When I am happy with my work, and its tested and working locally, I merge master into it:

git fetch && git merge origin/master && rake spec

This command gets the latest version of master, and applies any new changes to my code base. Master is not changed. I run all my tests again, and then deploy to stage-laurie. I then pass this over to my quality assurance guys (which could be me in another hat, but we were lucky enough to have a secondary team of people who were in a position to do the testing instantly). They test the product, checking that the feature has been added correctly, or the bug fixed, and that no new bugs have been introduced (though your unit tests will catch that - right?). This is continuous integration happening right here.

Git work-flow

After I have gotten my code to a point where this all passes, I push the state of my local branch to origin/laurie, and I go and talk to the gatekeeper.

In our team the gatekeeper was a person, though if your brave you could automate him. The gatekeeper has a local master branch. After I have told him that the changes in laurie are good to go, he asks round the rest of the team. Are any other branches good to go, generally there will be about 2-3 branches ready to go at any one time. He then gets a summary of what the changes are, and orders them in order of business value. Then, starting with the most critical change, he merges it into master, and runs all the tests. He then does this for the next most critical fix and so on. If at any point one of the merge results in code that fails the tests, he can simply un-merge (moving the post it note mentioned in the Git for Computer scientist article, - you did read it I hope).

Other developers can help with this process on their workstations. After my changes (which are of course the most important) are successfully merged into master, everyone else can pull master again, and merge it back into their branch, - preempting any conflicts and fixing them.

Once the gatekeeper has merged in all the changes, or at least all the ones that don’t conflict and break tests, he deploys this to a master staging server. Once again the quality team takes a look, this time concentrating on making sure that no existing functionality has been blatted by any of the changes. Assuming that passes the gatekeeper then merges origin/master into origin/stable. Tags it with the latest release revision number, and deploys onto our production environment.

We found this flow worked really well. Conflicts and merge related issues did occur, but always when merging the master branch into a developers local branch, so at most one team member was held up by this.

We took the policy of releasing as often as possible, so we would often release a new production code-base 2-3 times a day, each time with fully tested code. Sure, there were a few mistakes, but even when we were making big change, and developing the work flow, no bug serious enough to need us to roll-back the production code got through the safety nets.

If you need to guarantee that there are no mistakes, then like any project, you need to increase the depth of your test phase. Ours was relatively fast, as most of the users were alpha/beta testers :)

Summary

Releasing production code that often was a great asset too. The management team could see that work was progressing. Even if it wasn’t going the speed they wanted (is such a thing possible) they were greatly comforted to know that the users would see several improvements per day. As a team we had the freedom to allow one or two developers to pick up a slightly longer scale project, such as refactoring an important sub-system while the rest of the team got on with pushing out live improvements, and of course the users got the experience of a system constantly being updated. As we were sensible with listening to the users before choosing the next piece of work, they also got the feeling that the application was very responsive to any change request they made.

No responses yet

Apr 30 2008

Polymorphic Associations and Interfaces In Ruby/Rails

Published by Laurie Tagged as:, , ,

I have been using a lot of polymorphic associations in rails recently. If you don’t know what they are, bear with me and I will explain in a moment. To really use a polymorphic association properly it’s vital to understand interfaces, which should be part of your daily bread and butter toolkit, but in a dynamic language like Ruby they are a conceptual construct, rather than a language enforceable construct, like in Java or C#.

So before I go on about interfaces, let me give you a quick overview of polymorphic associations.

A polymorphic association lets you associate your model to another object, model, entity etc (pick your word, they all mean the same thing really) without knowing its type. Think about a user holding a number of subscriptions, one might be an RSS feed, another a stream of Twitter message (via some fancy new API), and a third a binary feed representing your CPU usage for the last 20 minutes.

If you want to use polymorphic associations with this, you could do it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class User < ActiveRecord::Base
  has_many :subscriptions
end
 
class Subscription < ActiveRecord::Base
  belongs_to :producer, :polymorphic => true
end
 
class RSSFeed < ActiveRecord::Base
  has_many :subscribers, :as => :producer, :class_name => "subscription"
end
 
class TwitterFeed < ActiveRecord::Base
  has_many :subscribers, :as => :producer, :class_name => "subscription"
end
 
class CPUMonitor < ActiveRecord::Base
  has_many :subscribers, :as => :producer, :class_name => "subscription"
end

At the database level, the subscriptions table will have two columns for the association: producer_type and producer_id. A composite foreign key. A row in the subscriptions table will show something like producer_type = “CPUMoniter” and producer_id = 3. When you call the producer method in subscription it will load the row in the CPUMoniters table with ID 3.

So the polymorphic bit means that the type of thing you’re going to get back when you ask a subscription for its producer is unknown. It might be an RSSFeed, it might be a TwitterFeed, or it might be a CPUMoniter, or possibly anything else you can think of.

More formally, according to Wikipedia (which knows all) polymorphism “is the ability of objects belonging to different types to respond to method calls of the same name, each one according to an appropriate type-specific behaviour.”.

Put in dynamic, Ruby terms, this means I don’t care what I sort of model I get when I ask a subscription for its producer, as long as it goes quack I can treat it like it’s a duck.

This is where interfaces come in. Interfaces specify what I want the returned object to behave like, it could be a duck, or it could be a spaceship or maybe, just maybe, it could be a producer. In fact if you read though the ActiveRecord docs on polymorphic associations, you will find that “interface” is exactly what they call the parameter passed in the :as key of the params hash, and the first parameter to a polymorphic belongs_to association, and even the xxx_type and xxx_id columns in the database. This threw me quite a bit when I first looked at polymorphic associations, you have to declare that the association uses the producer interface, but you don’t have a producers model, or a producers table, or a producers anything for that matter. To my mind, “producers” is the name of the interface that RSSFeed, TwitterFeed and CPUMonitor all have to implement. It could specify that all of them must have a “next_message” method, which will give me (surprise surprise) the next message they produce. If I don’t have something like this, then my code is going to get messy:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Subscription < ActiveRecord::Base
  belongs_to :producer, :polymorphic => true
 
  def print_next_message
    if producer.is_a?(RSSFeed)
      puts producer.rss_message
    elsif producer.is_a?(TwitterFeed)
      puts producer.twitter_messsage
    else
      puts producer.cpu_message
    end
  end
end

Which is just really butt ugly. Its slow to grok to figure out what’s going on, and I don’t even want to think about maintaining that code when I add a CriticalNuclearReactor class that people can subscribe to. If on the other hand, I say that every thing which implements the producer interface must define a next_message method I can push the ugliness into the classes that implement the interfaces.

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
37
38
39
class Subscription < ActiveRecord::Base
  belongs_to :producer, :polymorphic => true
 
  def print_next_message
    puts producer.next_message
  end
end
 
class RSSFeed < ActiveRecord::Base
  has_many :subscribers, :as => :producer, :class_name => "subscription"
 
  def next_message
    rss_message
  end
end
 
class TwitterFeed < ActiveRecord::Base
  has_many :subscribers, :as => :producer, :class_name => "subscription"
 
  def next_message
    twitter_message
  end
end
 
class CPUMonitor < ActiveRecord::Base
  has_many :subscribers, :as => :producer, :class_name => "subscription"
 
  def next_message
    cpu_message
  end
end
 
class CriticalNuclearReactor < ActiveRecord::Base
  has_many :subscribers, :as => :producer, :class_name => "subscription"
 
  def next_message
    get_the_bloody_hell_out_of_here_message
  end
end

Just look at how much easier the print_next_message method in subscription is to read. This is good. Also notice how the only time I need to care what the technique for getting a message from a nuclear reactor is when I’m inside the nuclear reactor class, which means I’m already thinking about nuclear stuff. I no longer need to hold that in my stack when I’m working on how subscriptions work. Finally, my subscription model does not need to be changed when I add another producer type. This is important. Very important! As soon as anyone with even a mild case of featuritus gets near your code they are going to want to add stuff, and more often that not, that will mean adding new classes. If adding new classes means adding new branches to all your conditional logic, your stuffed. In that case write me a big cheque and I might come and fix your design for you.

So this is how interfaces work. In a static language (Java, C#) you can get the language to enforce this:

1
2
3
public interface Producer {
  public message next_message();
}

and your subscription class can (is required to) state its the type it expects for producer

1
2
3
public class Subscription{
  public Producer _producer;
}

and your compiler checks all this for you. If you get it wrong you get nice early TypeMismatchError. Now I’ve finally decided I prefer dynamic languages to static, so I’m not going to claim Ruby is crap for not allowing this. But it is a big stinking black hole you can fall into if your not expecting it.

In fact it’s not really a problem at all. All you have to do is write down, somewhere obvious, somewhere where anyone in your team is going to find it, what methods you expect producer to implement. If you can find a way to check what types could have been assigned to the producers association (analysing the code is too hard, but you could get a good idea by peeking into the database) you can even get your unit tests to check that all the classes that are going to be returned from producer respond to the next_method message. You could even write a module that you import into your producer classes that provides either a decent default implementation or raises “Interface Not Implemented Properly, shoot the coder” exceptions.

So that’s interfaces. Hopefully you know have a good idea of why they are very important when using polymorphic associations, even though you can’t code them (in Ruby), you should be thinking about them. Really.

One response so far

Dec 12 2007

Personal content, for just your friends.

Published by Laurie Tagged as:, , , , ,

Have you ever wanted to share something personal with just a few, or even just one close friend. Its really not easy. I’m not talking about an idea, something you can just ring up and tell them. I’m thinking of videos (though the idea extends to photos, or music, or any thing like that). Because its not easy, I think a lot of you end up not doing it, and thats a shame.

I spent today working on this problem. My dance partner and I had someone record us at a competition at the weekend. I want to share the videos with her, but not with the whole world. After all, what if someone in Australia sees it and doesn’t like our dancing! I didn’t want to burn a copy of the CD and give it to her. Mainly because I just had a foot operation, and so can’t get out of bed. That aside though, some sort of internet sharing is just so much more elegant, and being a computer geek, i want elegance when doing this sort of thing.

So video sharing, of course, means YouTube. Does YouTube allow me to share a video with just one person? It turns out it does, but falls very short on my elegance desires. I won’t bore you with all the details, but by the time I had set the video up to not be publicly viewable, and informed YouTube who, other than myself, should be able to view the video, I had formed a somewhat less than favorable view of the administration interface that YouTube provides.

I think this is really quite a big deal. The easier something is to do, the more I am willing to do it. Facebook makes tagging people in a photo really easy, so I tag photos in Facebook. My photo-library software though, just isn’t as good, its not bad, its just not *as* good, so I don’t tag photos in it. If I could easily send a video message to a group of people, and be sure only they get it, then I probably would.

The thing thats really important to me here is the idea of how confident I feel doing this. The more I trust the people I am sending my content to, and the more I trust the security of the system, the more open I will be, and the better the quality of the communication will be. I find I do trust YouTube (for now), but the lack of simplicity in their interface leads me to believe they either do not want, or do not care about user to user communication. I did use them today for my videos, but it did not leave me with the warm fuzzy feeling that they care about me. Nor did it leave me wanting to try sending videos to other friends.

One response so far

Dec 08 2007

Getting Naked

Published by Laurie Tagged as:

Its been some time since I last wrote anything. However I refuse to sit here and write down that its simply because I have been too busy. The real truth is I have been too mythered. Not enough taking control of my life. Just the other day I sat down and did some paperwork, and found unopened bank statements from as far back as June. Thats just not like me!

Those close to me always told me it would take about two years after completing my PhD to really recover. I laughed at that and thought it was stupid, but looking at the calendar I see that is has now been two years, and finally all my bank statements are filed. Just in case…

So what now, what changed? Well for starters I have just accepted a new job, which I will be starting in the new year. Check out www.getnaked.com for all the lowdown on the company and the team. We will be developing a open messaging platform, which, in short is going to let you use your online existence to really be open with your friends. Not in the way Facebook lets you keep track of all the people you lost touch with 15 years ago, but actually maintain and nurture friendships, encourage you to be open, honest and emotionally naked with those people you trust. This will tie into some thoughts I wrote about a couple of years ago now. My thinking then was inspired by a Joel on Software post on how the tools given to online communities can influence the culture of the community. I’m really looking forward to spending some more time thinking about these sort of things. So check out the naked site, and sign up for the beta program, which is launching soon.

The last year or so I have also been getting more and more into my dancing. I don’t write too much about that, partly because it doesn’t translate so well to written form, and partly because my partner is a private person, who would not appreciate it if I were to go into day to day details. But I’m enjoying it, we are making progress and have started to attend competitions regularly.

The last thing thats made me stop and think about things a bit is an up-coming operation. In 3 days time i have to go under the knife to have the bones in my little toes reduced in size. The operation itself is pretty minor, but i will have to spend 2 weeks in bed to let the bones fully recover before putting weight on them again. I have been rushing about so much trying to get all the little bits that need to be sorted sorted, and then I will suddenly go from running everywhere, to not moving for two weeks. I think I am going to feel like I have run straight into a brick wall! If anyone feels like sending me some nice messages, or better yet, visiting and keeping me company, it would be very much appreciated. Oh, and if you are coming. I prefer green grapes to red, preferably peeled :-)

No responses yet

Jul 30 2007

Rapid Prototyping for Java using JRuby: A Presentation

Published by site admin Tagged as:, ,

On Thursday 30th of August I will be presenting a talk as part of the LRUG BOF (Birds of a Feather) session at NFJS, No Fluff Just Stuff. It will be my first time presenting outside of an academic conference and I am really looking forward to it. I’m going to be talking about how JRuby can be used to rapidly prototype new features into a Java application.

I must admit, the biggest concern I have is about estimating the audience. It’s quite a varied conference, mainly Java and Agile, and it’s not clear what proportion of the audience will know anything about Ruby, and what proportion will be experts. Figuring out what level of understanding in each language to pitch the talk at is going to be an open question. It won’t be until I start the talk that I will really know if I have got it right.

The BOF session is free, but you need to pay if you wish to attend the rest of the conference. On the plus side, as valued readers of this blog you get a discount. Simply quote NFJS-BLO182 when you register and you get £100 off the registration fee.

NFJS Logo

No responses yet

Jul 23 2007

Using JRuby to rapidly prototype changes in a Java codebase

Published by Laurie Tagged as:, ,

Today, as an exercise, I coded up a simple piece of java and ruby integration, via JRuby.

The task I set myself was simple. Start with a java only application, and then use JRuby to rapidly prototype adding a new feature to it. I used my favourite sample application: A library with three entities, books, borrowers and loans (the first application design I was ever taught – way back in A-levels). The design is pretty simple; a borrower is associated to a number of loans, each of which is associated to a book. There is also a link from each book to all the loans it’s refereced in.

I intentionally made a limiting design decision however. Each book’s author is saved as a string, and the meaning is lost when someone tries to enter several authors to a book

public class Book {
<snip>
private String author;
<snip>
}

Book jrubyBook = new Book(”JRuby for beginners”,
“Ruby Guy, Java Guy”, //second argument is author
“12365437890″,
LoanType.ONE_MONTH);

The feature I wanted to add was the ability to look at a book, and see what books influenced its authors. The logic used is:

  1. use the book.author property to find out the author(s) of the book
  2. look at the loans associated with the author(s)
  3. get the books for those loans

Not a very complex piece of logic, but good enough to demonstrate the point. Ideally the author field of book should be refactored to be a collection of people which would be created as a new super-class of borrowers. But before I go and do some refactoring, (which in a real project would mean quite a bit of changing the persistence mapping too) I want to get the functionality working to see if it really is useful. JRuby’s ability to load up some java classes and quickly change them allowed me to simulate doing these changes.

require ‘java’

include_class ‘com.wildfalcon.library.model.Book
include_class ‘com.wildfalcon.library.model.Borrower’
include_class ‘com.wildfalcon.library.persistance.Books’
include_class ‘com.wildfalcon.library.persistance.Borrowers

class Book
def authors
author_names=[]
getAuthor.split(”, “).each { |author| author_names << Borrowers.findByName(author)}
author_names
end

def inspirations
list = []
authors.each {|author| author.books.each{|book| list << book}}
list
end
end

I can then call the inspirations method:

book = Books.findByName(”JRuby for beginners”)
book.inspirations.each {|a| puts a.title}

all of which I put in a prototype.rb file an execute as follows:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName(”jruby”);
InputStream is = new FileInputStream(new File(”prototype.rb”));
try {
Reader reader = new InputStreamReader(is);
engine.eval(reader);
} catch (ScriptException ex) {
ex.printStackTrace();
}

Indeed when I execute it I find out what books have been read by the two different authors of “JRuby for Beginners”:

  • Java for beginners
  • Ruby for beginners
  • How to tie a tie
  • History of fairy tales
  • Cooking Italian Food for Large Groups

This quickly allows me to realise that looking at the books read by the author isn’t good enough, before I can deliver the feature I need to find some way to tell which books are relevant and which are not. But I found that out with a very small amount of coding, and without having to make any changes to the existing java application. I can happily go back to the drawing board without worrying that I broke something in the meantime.

No responses yet

Jun 29 2007

Wildfalcon Relaunched

Published by Laurie

My website - with its new design, is now online.

I’ve been meaning to do something about the design of my website for ages. Finally I have. I was being held back by the way I run several different things I had on the site: My blog, my research history, my photos and a few other small things. Each of which was effectively written as its own independent little mini website, with a visual design that spanned all of them. Changing the design would have meant updating all the different sites with the same design. To put it another way, I had taken out a large technical debt on the site by having all the things written and managed separately.

While this has been going on, Wordpress, which is the blogging software I use, has slowly been getting better, and better – more able to handle all the different things I want to do. So this week I bit the bullet, and transferred the most important parts of the web site – the bio and research publications into Wordpress. I then spent a bit of time finding and modifying a theme for Wordpress that I liked, and the result is now live, though I need to find a higher resolution copy of the banner image. Finally I have paid off the technical debt on my website. I can now modify the design and add features much much easier.

I still haven’t transferred the photos, though my analytics tell me that not many people are looking at those at the moment. I’m far from convinced I can find a way to integrate a photo gallery nicely with Wordpress, but to be honest, I haven’t yet seen any photo based site or web service that meets all my requirements, so I’m probably asking too much there.

As for what next, well I am enjoying writing down random ideas, but I feel that I am covering a few too many ideas, and not concentrating enough on what really interests me, which is how the various, apparently unconnected ideas can be interrelated. So I’m going to try and concentrate a bit more on that. Though who knows, I may well need to put up a few more ideas before I can start to show the similarities between them.

No responses yet

Jun 10 2007

Stuff your Java model into your Rails project

Published by Laurie Tagged as:

The upcoming, and now recent, release of JRuby 1.0, along with some conversations with various friends has left me thinking a lot recently about how to integrate a Java project with a Ruby (on Rails) project. If you have an existing domain model written in Java then the reasons you might want to do this become obvious. Rails is designed using the MVC architecture, and if you can get it talking to your java domain model, then the M is already written for, you just have to write the views and controllers. Views especially can be painful in Java.

The standard answer for integartion between languages is currently web services: Write a simple XML wrapper round the Java domain objects allowing methods to be called on them, then use that API from within your Rails models. It doesn’t really matter if you use SOAP, REST or your own “standard” (although REST lends itself nicely to having a toXML() and a setXML() method on your java classes and using ActiveResource to GET and SET instances).

However, XML has never been a major contender for speed, and the chances are that your API isn’t designed to minimize the number of calls you make. So you have to pay that overhead more often than you need to. Of course you could add a remote facade, but now things are maybe starting to get more complex than you need…

JRuby provides a much more integrated way of solving the problem. It works like this: JRuby lets you import Java classes into your Rails code. Your controllers do not need to know (or care) that they are not Rails models. They can just find a new User instance, set the password on it, and move on to the next one.

Of course, I’m not suggesting that it’s that simple. Rails expects the models to be ActiveRecord instances. You are likely to suffer from code expecting to find an ActiveRecord method, like User.find and it not being there. I imagine the solution to this would be a library that loads all of your Java classes, and then changes them (as Ruby can do that) to add methods normaly provided by ActiveRecord. You can add the validation methods, then you can add the persistence methods like save, and find. How you do this is going to be dependent on how your Java persistence is done (ok, I’m assuming your Java code has a persistence model - I probably should have mentioned that earlier). If you have used the DAO pattern, the find method could instance a DAO object, load an instance though it, and return that. If you don’t use DAOs, then you map the methods to whatever you do use.

Finally you need to wrap all your code up into a library that runs when rails starts, automatically loads all your java classes, and decorates them. Hey presto, your old legacy Java domain model has a new lease of life as a trendy Rails application. If anyone has the time to write this library, let me know - I would love to have a play with it.

Unlike the rest of the Rails system, this integration won’t be solved by convention over configuration. Potentially it could be, but I think there are just too many different designs; different persistence models and different ways of locating your domain model out there…

2 responses so far

Feb 28 2007

New Post, New Photos

Published by Laurie

Well I have posted anything for a while, which to my suprise several of you nice people commented about while I was at SUDC this weekend. The main reason is that I had a stomach bug/food poisoning incident a few weeks ago, then was hit by two colds in a row, that’s in addition to the one I had before the stomach bug. So i haven’t really been up for writing. The spare energy I have had has gone into dancing. Which after a rather difficult start (from a getting lessons point of view) is finally starting to go well.

But enough about me, if the MSN messages and Facebook messages I have been getting for a while are anything to go by, then all you guys care about is when you can see the photos. So you will be glad to know that the SUDC Photos are now Online. If you are on Facebook then the best 50 or so have also been uploaded and tagged there.

I’m starting to feel better now, I’m already thinking about writing something about conceptual models in general, not just scientifical, logic based models, and how useful it can be (and sometimes painful) to have your model of something shifted to a new model. Stay tuned…

No responses yet

Next »