Friday, May 23, 2008
I have a small fantasy football related project that I'm going to be working on that requires access to the full 2008 NFL Schedule.  I decided to use Hpricot, and scrape the schedule from ESPN.  The CSV file I created with the output from the below script can be found here: nfl-schedule.csv (11.48 KB)  

Download script (parse_schedule.rb)

#!ruby
require 'rubygems'
require 'hpricot'
require 'open-uri'

class Game
   attr_accessor :date, :week, :away_team, :home_team, :time

   def to_s
      "#{@date} #{@time} #{@away_team} at #{@home_team}"
   end

   def to_csv
      "#{@week},#{@date.gsub(",", "")},#{@time},#{@away_team},#{@home_team}"
   end
end

def parse_games(doc)
   games = []
   doc.search("//table[@class='tablehead']//tr").each do |tr|
      @week = tr.search("/td/a").inner_html if(tr[:class] == 'stathead')
      @date = tr.at("td").inner_html if(tr[:class] == 'colhead')

      teams = []
      tr.at("td").search("a").each do |team|
         teams << team.inner_html
      end

      if(teams.size == 2)
         @time = tr.search("td:eq(1)").inner_html
         game = Game.new()
         game.date = @date
         game.week = @week
         game.time = @time
         game.away_team = teams[0]
         game.home_team = teams[1]
         games << game
      end
   end
   games
end

games = parse_games(Hpricot(open("http://sports.espn.go.com/nfl/schedule")))
games.each do |g|
   puts g.to_csv
end
puts "Total games: #{games.size}"
Saturday, May 24, 2008 12:35:58 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [4]  |  Trackback
 Thursday, May 08, 2008
In preparation for my upcoming Code Camp session on IronRuby I've been hacking around on the IronRuby source, as well as on Ruby programs that can run on IronRuby.  One of the core areas of interest for me concerning IronRuby is in writing specifications for my .NET applications using Ruby.  While I've been learning Ruby (the real kind) I've become very fond of the testing libraries they have available, most notably RSpec and mocha

Over the last two nights I've been writing some ruby code to test .NET classes written in C#.  With a few of the hacks I have locally, I've had some pretty good success.  The following set of specifications verify the behavior of an Account class I've written.

require "../../trunk/tests/ironruby/Util/simple_test.rb"
require "IronRubySamples"
include IronRubySamples

describe "Account" do
    describe "When depositing money into my account" do
        it "should increase my balance by the amount deposited" do
            account = Account.new(10)
            account.Deposit(10)
            account.Balance.should == 20
        end
    end
                               
    describe "When withdrawing money from my account" do
        it "should decrease my balance by the amount withdrawn" do
            account = Account.new(100)
            account.Withdraw(50)
            account.Balance.should == 50
        end
    end
                   
    describe "When withdrawing money from an account with insufficient funds" do
        it "should tell me I have insufficient funds" do
            account = Account.new(30)
            should_raise(InsufficentFundsException) { account.Withdraw(50) }
        end
    end
   
    describe "When making a withdraw that drops my balance below the minimum" do
        it "should reduce my account by the amount withdrawn + the low funds charge amount" do
            account = Account.new(55)
            account.Withdraw(50)
            account.Balance.should == 4
        end
    end
end

The next step in my quest to test .NET code with IronRuby required me to figure out how to mock out dependent objects.  I considered several different options.  My first thought was to try and use "simple mock", however, I quickly realized via Scott Bellware that while it worked well on IronRuby libraries it wouldn't fit my needs.  My next thought was to give Moq a try.  After downloading Moq, I attempted to run a spec that referenced Moq and created a Mock<T> instance as shown below:

require "../../trunk/tests/ironruby/Util/simple_test.rb"
require "IronRubySamples"
require "Moq"
include Moq
include IronRubySamples

describe "LoginController" do
    describe "When a user logs in" do
        it "should vallidate credentials with login service" do
            mock = Mock.of(ILoginService).new
            #do expects
           
            controller = LoginController.new(mock.Object)
            controller.Login("steve", "****")
        end
    end
end

When running this via ir.exe I got an error that "Moq.Mock is not a generic type".  After poking around a bit I discovered this was due to a bug in IronRuby.  Currently IronRuby has problems when there is a generic and non generic type of the same name within a referenced assembly.  In order to work around this, I first tried to figure out what needed to be modified in IronRuby, however, that wasn't very fruitful so I decided to modify the source for Moq to get around my problem.  After renaming the static Mock class in Moq to MockRetriever, and hacking around another bug in IronRuby related to creating generic types where the type argument is an interface, I was finally able to get IronRuby to create the Mock<ILoginService> type:

mock = Mock.of(ILoginService).new

Unfortunately, this led to me to another roadblock.  When setting up expectations in Moq you do so with lambda expressions such as:

// C#
var mock = new Mock<ILoginService>();
mock.Expect(s => s.Login("steve", "****"));

While IronRuby has blocks and lambda's it doesn't have a way to express the above (at least that I know).  I'm going to dig around in the IronRuby source a bit to see if any ideas pop into my head, but at this point I'm not very hopeful. 

 |  | 
Friday, May 09, 2008 1:09:46 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [2]  |  Trackback
 Sunday, April 20, 2008
As I continue on my quest to get more information about IronRuby, I figured it was worth figuring out what needs to happen in order to contribute code back into the project.  The source code for IronRuby is synced with RubyForge every so often, and patches to the source code can be submitted on the RubyForge project here.  Before making any contributions to IronRuby a contributor agreement must be electronically signed.  John Lam's post to the IronRuby mailing list can be found here, and the actual agreement is available at: http://www.ironruby.net/contributor.pdf

The agreement appears to be pretty staight forward, the main point worth attention is that you grant Microsoft all rights to the contribution.
For good and valuable consideration (including without limitation the opportunity to contribute to the Project), receipt and sufficiency of which is hereby acknowledged, Assignor hereby assigns and agrees to assign to Microsoft its entire right, title,
and interest (including all intellectual property rights) in the Contributions.

Microsoft then licenses the contribution back to you to do with it as you wish.
Microsoft grants You a non-exclusive license under the rights assigned to Microsoft in Section 3 to use, reproduce, modify, license or otherwise distribute, and exploit the Contribution as You see fit.

If you're interested in contributing you need to send an email to ssiadmin at microsoft.com requesting to be added as a contributor to the IronRuby project.  I sent an email this morning so I'm not sure what happens next, but I'm assuming the electronic signing of the contributor agreement will be the next step.

Sunday, April 20, 2008 12:31:37 PM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, April 19, 2008
I've been digging around IronRuby a bit lately, checking out the source, the specs, and writing very minimal code into rbx to see if it works as expected.  Over the next couple weeks I'm going to try and dig a little deeper into IronRuby in an attempt to get a better feel for where it is, what I might be able to use it for, as well as to experiment with some ideas I've had over the last couple months. 

When I first downloaded IronRuby I did so on my Mac in hopes that I'd be able to cruise around the source in TextMate, compile with Mono, and avoid having to fire up a VM whenever I wanted to experiment.  My initial attempts, albiet not very focused, were a failure.  Fortunately within the last week or two I came across Seo Sanghyeon's IronRuby on Mono How to.

The first step is to download and install Mono 1.9.  Once you have Mono installed you need checkout the IronRuby source from RubyForge and then download and apply this patch that Seo created.  Finally run: rake compile mono=1 and assuming everything goes well you'll be greeted with another command prompt which you can use to fire up rbx (aka IronRuby's irb) and begin experimenting.
svn co http://ironruby.rubyforge.org/svn/trunk ironruby
cd ironruby
patch -p0 < patch-mono-r93
rake compile mono=1
mono build/mono_debug/rbx.exe

Saturday, April 19, 2008 1:56:03 PM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Tuesday, March 18, 2008
Tonight I was chatting a bit with a co-worker about IronPython and IronRuby and decided to have a look at IronRuby.  Getting started is supposed to be pretty easy.

1. Checkout the IronRuby source from RubyForge

svn co svn://rubyforge.org/var/svn/ironruby

2. Install Ruby via the Ruby 1-click installer: http://rubyforge.org/projects/rubyinstaller/
3. Open a Visual Studio Command Prompt
4. Install the pathname2 gem by running the following from the command line:

gem install pathname2

5. Compile IronRuby by running:

rake compile

Unfortunately when running "rake compile" I get the following errors.

C:\Development\ironruby\trunk>rake compile
(in C:/Development/ironruby/trunk)
Read in 17 resources from "C:\Development\ironruby\trunk\src\microsoft.scripting
\Math\MathResources.resx"
Writing resource file...  Done.
Read in 49 resources from "C:\Development\ironruby\trunk\src\microsoft.scripting
\Resources.resx"
Writing resource file...  Done.
rake aborted!
Command failed with status (0): [csc /nologo /noconfig /nowarn:1591,1701,17...]
C:/Development/ironruby/trunk/rakefile:197:in `exec'
(See full trace by running task with --trace)

I did a little digging around to see if I could find out what was causing the above problem but didn't uncover anything.  In hopes of making some progress and seeing ruby running on top of the CLR, I decided to try and compile using the IronRuby VS.NET solution file. Compiling IronRuby using the VS.NET solution file built everything into the \bin\debug folder.  Once that was done I was able to run rbx.exe and do a little experimentation.  rbx didn't behave like I expected and seemed to be acting pretty flaky but I was able to put in some simple Ruby expressions and see the results I expected.  Now that I have the source downloaded and compiled I'm going to dig into things a bit more to see where things stand. 

Some resources that I came across that might be useful to others include:

 |  | 
Wednesday, March 19, 2008 2:44:25 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [2]  |  Trackback
 Wednesday, September 12, 2007
Over the last year I've spent a lot of my "free" time with LINQ.  When not writing and/or experimenting with LINQ I've been trying to learn Ruby.  Since I'm primarily a Microsoft guy, I've spent time in some Microsoft "friendly" Ruby communities such as SoftiesOnRails. As I think is typical in most passionate technology oriented communities, most Ruby peeps aren't real big fans of Microsoft.  I've heard numerous people in the Ruby community discount all things Microsoft, which led me to wonder if any Rubyists would ever give LINQ a fair look.  A couple weeks ago I came across Chris' "Full of Ambition" post on the err the blog site.  As soon as I saw ambition, I thought to myself "hey, it's LINQ for Ruby".  From reading over the initial post, it didn't sound like the guys behind ambition where inspired by LINQ at all, but instead were gunning for Rack.  A noble ambition, but surely LINQ would be a better and more ambitious goal!  Well it turns out that since their initial post the gents behind ambition have found LINQ, and set it as their new target!  In their most recent post about ambition they state:
We’ve moved our sights from Rack to LINQ. That is, we don’t want to only support other ORMs—we want Ambition to be a query language for SQL, LDAP, XPath, the works. The 1.0 release will be backend-agnostic. Maybe then we’ll change the name to Hubris? Time will tell.
As a big fan of both LINQ and Ruby I'm glad to see some LINQ'ness finding it's way into Ruby. 

Links:
Intro to Ambition
Update to Ambition, with LINQ as the new target
 | 
Wednesday, September 12, 2007 5:27:04 PM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [2]  |  Trackback
 Thursday, August 16, 2007
I just registered for Ruby East, which is being hosted by Chariot Solutions a hop, skip, and jump from my house!  Hopefully it will be a good time!  They appear to have a number of good speakers lined up to talk about some interesting topics.

 | 
Friday, August 17, 2007 12:30:26 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, August 04, 2007
Keeping with their trend of publishing great Ruby content, InfoQ recently published a video of Fred George from Thoughtworks, talking about "Applying Agile to Ruby".  In his talk, Fred talks about how important many of the core agile practices are when working in Ruby.  Since Ruby is a dynamic language and doesn't offer some of the "safeguards" that statically typed languages provide, agile practices such as test driven development (TDD), continuous integration, and simple design become even more important.  Fred closes his talk with the following statement: "I wouldn't work on Ruby without Agile".  I wonder if he'd work on C# or Java without Agile.

Sunday, August 05, 2007 2:34:03 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, July 28, 2007
James Avery poses an interesting question in his "How long before ALT.NET becomes NOT.NET?" post.  I'm not really sure what it takes to get into the ALT.NET club, but from what I know I'm guessing I'd fit into the general "demographic".  Like James, I've also been wondering if and when more of the ALT.NET'ters will turn to Ruby on Rails (or alternates like Django).  I've thought about this a bit more lately since I've been spending a lot more time in Ruby and Rails.  In addition to wondering about other ALT.NET peeps, I've also thought a bit about where I want to go with my development efforts and whether I want to continue to focus on .NET as my primary means of making a living. At this point I don't see myself doing anything drastic.  Considering I only have 2 Rails projects under my belt and a heck of a lot more to learn about Ruby as well as Rails I think that's a pretty wise course to take.  I am going to continue on my path to learning Ruby as best I can, afterall it is my language for 2007.  I'm also going to continue to do projects with Rails, try and write a lot more Ruby and Rails related code from scratch (plugins make life way too easy), and evaluate if there is anything I've learned from Ruby and Rails that I can bring over into my .NET related work.  I'm also going to be keeping a close eye on IronRuby, and anxiously awaiting the day when they announce they can run Rails on top of it! 

At the end of the day, I believe learning Ruby, Rails, as well as many of the other things I'm looking into, will make me a better developer.  Whether or not I end up building the software I work on in .NET, Ruby, or Erlang doesn't matter much.  I think we all owe it to ourselves, as well as our customers, to question whether what we're using today is the best tool for the job.  We also owe it to ourselves to question whether we'd find more enjoyment in working with other languages and tools.  After all those questions are raised and answered we still need to make a decision based on where we are in life, what we have control over, and where we want to go in the future.

Perhaps before the migration to Rails starts, Microsoft will change its ways and learn a thing or two about what it takes to make ALT.NET developers happy.  Perhaps they'll realize that designers, wizards, and other magic isn't what where it's at.  Perhaps they'll realize that baking best practices into the platform is a good thing.  Perhaps they'll have a look at TextMate and realize it doesn't have any designers, yet Rails developers love it?!?!?  Perhaps they'll learn a thing or two from the success of Rails and stop the floodgates from opening.  What do you think?


 |  |  | 
Sunday, July 29, 2007 2:45:36 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [4]  |  Trackback
 Monday, July 16, 2007
Over the weekend I listened to the latest .NET Rocks episode with John Lam.  I'm very keen on seeing and hearing about where the IronRuby project is going, so I found the interview very informational.  Although I enjoyed the entire show, one particular exchange between Carl and John stood out.  About half way through, Carl asked John whether he thought developers who don't do test driven development (TDD) and unit testing should be working in dynamic languages.  John made the wonderful assertion that he doesn't believe programmers that are not writing "unit tests" should be writing code in any language, regardless of whether the language is dynamic or statically typed.   Following that statement, John went on to mention that whether or not the code is test driven isn't nearly as important as whether the code has unit tests since the "test driven" approach is "extreme" and "dogmatic".  While I agree that the key is unit tests, I don't agree that a test driven approach is extreme or dogmatic.  In my opinion its the most pragmatic approach to writing code that is well designed and well tested.  The fact is, writing unit tests after the fact sucks!  Especially if "after the fact" is days or weeks after the real code is written.

When I first got started with TDD I didn't really understand what it was all about.  Rather than figure out what this magical red-green-refactor thing was all about I decided I'd just write some unit tests once I had my code written.  After a couple projects using this approach I started to realize that I really hated writing unit tests after the fact.  It was because of this hatred that I got started with test driven development.

Rather than testing being a pain in the ass task that I had to do when I finished writing my "real" code, testing became an instrumental step within the process of writing the "real" code.  Since I was using tests to figure out what code needed to be written, it became a vehicle by which I could design the code I was writing, rather than an afterthought.  I'm sure there are people out there that write great tests after the fact, however, I'm not one of them.  For me writing tests first isn't something extreme or dogmatic, it simple the only way I can write high quality code with solid test coverage without going nuts.  For me, writing unit tests after the fact sucks.  For me, driving my code with tests is a joy. 

I wonder how writing tests first could be "extreme" and "dogmatic" for others, but for me its pragmatic?

   
 |  | 
Tuesday, July 17, 2007 3:58:39 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [17]  |  Trackback
 Wednesday, July 11, 2007
As I've stated before, my programming language for the year is Ruby.  I actually planned on learning Python or Ruby last year, but things didn't pan out.  Over the last 6-8 months I've been doing a pretty good job of getting myself on the way to learning Ruby.  As with any language the best way to learn it is to write something using it.  As we all know Rails has done a tremendous job of bringing people to Ruby.  I'm no different.  Over the last 6 months I've worked on two Rails projects and in the last week put one of them into production (well almost).  Since I'm half way through the year I wanted to put some thoughts down here, mostly for myself, but also for others who might be interested in a .NET dudes impressions of Ruby and Rails.

Before writing a book myself, I bought a good number of books on technical topics that I found interesting.  After experiencing what goes into writing a book, I find that I'm much quicker to pull the trigger on books that I think I might find interesting.  The amount of work required to get a book out the door is mind boggling to me.  As such I've purchased, and read, the following books to help me learn Ruby.
As you can see not all the books are strictly Ruby related.  Several are focused on Rails, one is focused on working with Google Maps with Rails, and one is to help me learn to work in my new favorite editor, Textmate.

In addition to reading the above, I've been checking out the source code for a couple of the more popular open source Rails applications as well as some of the more popular plugins.  While all of that has been very valuable, nothing is ever as good as actually writing code.  As such I've done several projects that I would have traditionally done in .NET in Rails instead.

The first application that I got started with (and which I'm still working on) is an application that helps geographically visualize key individuals within a social network.  The data for the individuals in the social network, as well as the data for the connections between individuals, is stored in flat files so I got my first chance to play around with the CSV parsing capabilities of Ruby.  I found the FasterCSV library very useful, and got off to a pretty good start with my first attempt at parsing the CSV files and getting them into my MySql database using my ActiveRecord model objects.  After the file parsing was done, I got a chance to build several administrative pages for the site using Rails, as well as the chance to experiment with some very useful plugins such as:
My second application involved setting up a site with paid membership.  The site has several administrative functions for the owner of the site, as well as a handful of features for those who sign up to be members such as exclusive downloads, advertising opportunities, and a members only forum.  In addition to be able to gain a lot more experience with the inner workings of Rails this project also led me to gain experience with:
So given all of the above, if your still reading, I'm guessing your wondering what I think.  In short, I'm becoming a pretty big fan of Ruby as well as Rails.  While Rails isn't perfect it does a lot of things very well.  Rails Migrations are the best solution that I've come across for migrating the schema of a database.  I can see why large teams run into some trouble with them, but for the projects I've been working on migrations have worked wonderfully.  While I'm a big fan of DDD, I also really like ActiveRecord in the right situations.  Being able to create a migration, run rake db:migrate, and have the column automatically available in my model without having to do anything makes developing with Rails and ActiveRecord very enjoyable.  Rather than dealing with the mundane tasks of writing scripts for adding columns, and then updating the associated data access and model classes, I can focus on the stuff that matters.  In addition to migrations and ActiveRecord I'm also fond of ActionMailer and the way that it allows you to create and send email, its far better than what's available in .NET land.  Next up, is the MVC structure that Rails uses for building the pages that make up the application/site.  I'm a huge fan of MVC/MVP for building UI's so it should be no surprise that I'm also a big fan of Rails implementation of MVC.  I really like having a single controller per model object, and having a nice organization to the views used by the controller.  I also really like the validation story for Rails.

As I learn new technologies I often times hack my way around until I get a good feel for what I'm doing and how things are supposed to work and be put together.  This led to me not writing as many unit tests for certain parts of the applications I was working on.  I did test drive most (if not all) of the logic I put into my model objects, but I slacked off a bit when it came to testing the controllers.  This is partly due to the fact that I was using scaffolding, and partly due to the fact that I was pushing almost everything into my model objects rather than allowing my controllers to get "fat".  As part of the test driving of my model objects I used the built in testing infrastructure, although I still want to checkout rspec.  On my latest project I also began experimenting with mocha which really helps with the testing of objects that have dependencies. 

So given all my recent exposure to Ruby and Rails one has to wonder how I rate it against my native "tongue", .NET.  I have to say I've had a lot of fun working with Ruby and Rails.  This is in part because its something unfamiliar and I really enjoy learning, but its also because both Ruby and Rails have a way of making developing with them very enjoyable.   I haven't enjoyed some of the deployments and such that I've had to deal with, but since I was learning a bit about how to deploy Rails applications on Linux it wasn't as bad as I expected.  I'm nowhere near hanging up my .NET toolbelt, but I am going to continue to do a lot of the work that I would have previously done in .NET in Ruby and/or Rails.

 |  | 
Thursday, July 12, 2007 3:11:07 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [3]  |  Trackback
 Monday, July 09, 2007
Glenn Vanderburg's "The Beauty of Ruby" JAOO presentation was recently published on InfoQ.com.  Glenn talks about some of "the subtle beauty that experienced Rubyists have come to know and love".  Over the last couple of months I've come across a lot of great content on InfoQ's Ruby section that has helped me to learn some of the subtle gems that exist within the Ruby programming language.  While reading books, and writing Ruby code are great ways to learn Ruby, its also tremendously valuable to hear experienced Rubyists talk about what they love about the language.  Below are a couple of my favorite Ruby presentations available on InfoQ.

 | 
Tuesday, July 10, 2007 12:46:49 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |  Trackback
The self proclaimed ninja's over at ActiveReload have unveiled Warehouse, a "web based subversion browser that doesn't suck".  Warehouse is a Rails app that allows you to view a subversion repository with a very slick web interface.  Rick and Justin spent the weekend when they weren't at RailsConf getting Warehouse started, and now a couple months later they've released it to the world. 

Tuesday, July 10, 2007 12:39:43 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [2]  |  Trackback
 Thursday, June 28, 2007
As Aaron mentions, one of our colleagues recently posted a "brain teaser" on the whiteboard at work.

A/BC + D/EF + G/HI = 1

All variables are unique digits from 1 - 9. Two variables next to each other is equivalent to 10 * var1 + var2. For example, if B = 2, C = 5 then the result is 10 * 2 + 5 which equals 25.

Since my language of this year is Ruby, I figured out the answer with the code below.  I had some of the code sketched out in my head, but I wrote it after seeing Aaron's post last night, so the way I went about implementing it pretty much matched the approach Aaron took.   I should also mention that I'm a Ruby newbie so there might be better ways to go about writing the below code.  If so, I'd love to here them since I'm still learning what idiomatic Ruby is :)

#!/usr/bin/env ruby
class FigureItOuter
  def run
    set = generate_set
    while (calculate(set)) != 1
      set = generate_set
    end
    puts format("%d/%d%d + %d/%d%d + %d/%d%d = 1", set[0], set[1], set[2], set[3], set[4], set[5], set[6], set[7],set[8])
  end 
 
  private
  def calculate(s)
    (s[0] / (10 * s[1] + s[2])) + (s[3] / (10 * s[4] + s[5])) + (s[6] / (10 * s[7] + s[8]))
  end
 
  def generate_set
    s = []
    while s.size != 9
      n = rand(9) + 1
      s <<  n.to_f unless s.include?(n)
    end
    s
  end
end

# a/bc + d/ef + g/hi = 1
f = FigureItOuter.new
f.run


Thursday, June 28, 2007 10:59:49 PM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Wednesday, June 20, 2007
I'm in the process of deploying a Rails app, and up until a few minutes ago I was having problems getting acts_as_attachement and attachment_fu to work.  I originally started development with acts_as_attachement since I was naive and didn't know there was something better.  After looking for a fix for the issue I was seeing, I came across attachment_fu and came to see that it was superior and would undoubtedly solve my issue.  It didn't....however, the upgrade process was painless and I got some extra goodies so all was good.  For those interested, the extra goodies include pluggable image processors (RMagick, MiniMagick, and ImageScience) as well as an option to store files with Amazon S3.

With attachment_fu installed, I was sure my problem would be resolved.  I suspected the issue I was having was related to RMagick image resizing since I'm deploying to a shared hosting account on TextDrive, and RMagick has quite a reputation for hogging up lots of memory and causing havoc on shared accounts.  After switching over to attachment_fu and to MiniMagick as my image processor I was still seeing my issue, so I realized it had to be something else.

Before going onto the solution, let me explain the problem that was occuring.  When I was submitting a form for an attachment_fu model I was immediately being redirected back to the index page.  Every once in a while the form would appear to be submitting, hang, and eventually hose the lighttpd process.  As I mentioned above, I first suspected the problem was related to image resizing being done by RMagick but I was able to reproduce the problem on a non image attachment_fu model object.  After digging around on the web and coming up empty, I ended up checking out the Rails log file to see if I could figure out what was going on.  Examining the production.log showed that I was going from the :new action, directly to the :index action.  Since I was submitting a form, I should have seen a hit on the :create action for my controller.  This led me to search google for a slightly better phrase which eventually landed me at this "Form doesn't trigger create in production" forum post, as well as this related post on Ruby Forum.

It turns out the problem is due to the way that attachment_fu stores the files uploaded on the file system.  attachment_fu stores the files in a folder with the same name as the model within the public folder.  This causes issues since the url for the controller, as well as the directory for storing files have the same URL.  Fortunately the fix is as simple as adding the following to your application.rb file.
def default_url_options(options)
{ :trailing_slash => true }
end

Deployment is such fun, isn't it! :)


 |  | 
Thursday, June 21, 2007 2:03:58 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [4]  |  Trackback
 Tuesday, June 12, 2007
The validation infrastructure within Rails is another one of the niceties that it provides.  By decorating model classes with validation helpers you can quickly define a pretty thorough set of validations for a model.  As an example of the types of validations that can be added to Rails models lets take a look at a user model created by the acts_as_authenticated Rails plugin.

class User < ActiveRecord::Base
  # Virtual attribute for the unencrypted password
  attr_accessor :password

  validates_presence_of     :login, :email
  validates_presence_of     :password,                   :if => :password_required?
  validates_presence_of     :password_confirmation,      :if => :password_required?
  validates_length_of         :password, :within => 4..40, :if => :password_required?
  validates_confirmation_of :password,                   :if => :password_required?
  validates_length_of       :login,    :within => 3..40
  validates_length_of       :email,    :within => 3..100
  validates_uniqueness_of   :login, :email, :case_sensitive => false

  #other stuff
end

By using validates_presence_of, validates_length_of, validates_confirmation_of, and validates_uniqueness_of we're able to put together a detailed set of validation rules for our User model.  Additionally, we can enable and disable certain validations by defining an :if parameter on our validations.  With all these things in place Rails provides a nice default set of functionality for ensuring the validity of models.  One of the things that's been on my mind since I started working with some of these validations is how they might scale, and how well they'd support a model object with complex validation rules.  While it seems as though what's provided out of the box by Rails could be bent in order to meet most requirements I came across something today that looks very promising.

The ActiveSpec project aims to provide domain driven design (DDD) style specificiations to the Ruby world.  While Rails is getting all the attention, ActiveSharp isn't limiting itself to Rails, but instead makes itself available to all of Ruby.  On my train ride home tonight I read through the Introduction to ActiveSpec and was pretty excited about the direction it's headed.  It's pretty early in the game so the current bits may not be ready for prime time, however, that doesn't make them any less promising.  In addition to providing the ability to create simple specifications, composite specifications, ActiveSpec also provides a base ActiveSpec class with macros to help make the process of creating complex specifications more straight-forward.  I've included some sample code snippets below, but to get a full run down of ActiveSpec checkout the Introduction.
# Composite Specifications
spec = CompositeSpecification.new
spec.add_specification(SizeSpecification.new(6, :username))
spec.add_specification(CollectionSpecification.new(18..30, :age))
spec.add_specification(ConfirmationSpecification.new(:password))
spec.satisfied_by?(User.new)
#=> false


# Custom Specification Class
class UserSpecification < ActiveSpec::Base
requires_presence_of :username, :password
requires_size 6, :password
requires_confirmation_of :password
requires_inclusion_in 18..30, :age
end

UserSpecification.satisfied_by?(some_user)

# pure ruby selection
User.find_by_specification(SomeAdvancedUserSpecification)

# specifications for SQL queries?
User.find(:all, :conditions => SomeAdvancedUserSpecification.to_sql)
 | 
Wednesday, June 13, 2007 3:18:44 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |  Trackback
I must say I'm growing more fond of Rails the more I use it. It seems like it was actually designed by someone writing real applications for a living, and designed to make the common things that we have to do in most applications straightforward and easy.  Tonight I needed to add some logic to send out emails so I read through the ActionMailer chapter in Agile Web Development with Rails.  For those interested, sending out emails in Rails requires that a mailer class be created that inherits from ActionMailer.  The easiest way to do this is to run the mailer generator like so:

script/generate mailer OrderEmail confirm_order

The generator creates a mailer object in the models folder of your Rails application that looks like so:

class OrderEmailer < ActionMailer::Base
  def confirm_order(sent_at = Time.now)
    @subject    = 'OrderEmailer#confirm_order'
    @body       = {}
    @recipients = ''
    @from       = ''
    @sent_on    = sent_at
    @headers    = {}
  end
end

Which we may modify to have the necessary settings, and accept the necessary order parameter like so:

class OrderEmailer < ActionMailer::Base
  def confirm_order(order)
    @subject    = 'Thank you for your Order'
    @body       = {:order => order}
    @recipients = order.customer.email
    @from       = 'steve@sellscoolstuff.com'
    @sent_on    = Time.now
    @headers    = {}
  end
end

The generator also creates a rhtml template for the email in the views/order_mailer folder that can be used to construct the email message.  To send the email is simply a matter of calling the deliver_confirm_order method on OrderMailer.  Take notice that we call deliver_confirm_order and not just confirm_order.  Rails supports either sending emails out by using the deliver_ prefix, or allows the emails to be created by prefixing the mailer method with create_. What's really nice is that the Mailer uses a rhtml template within the views directory for the mailer (views/order_mailer in the example above) to generate the email.  This allows you to create emails using the same mechanisms used to create dynamic pages within Rails.  Plain text emails can be created, or the mailer methods and views can be updated to pass along parameters, which we do above with the order parameter.  The only difference between a mailer template and a template for a controller is that the mailer view is being used to create a text email rather than an HTML page that will be rendered to the browser.

With my mailer in place I had everything I needed to send out the necessary emails.  There was only one problem, on my MacBook Pro the emails I was generating weren't sending.  Luckily I was able to find this page on how to get OS X setup to send emails via SMTP.  After following these steps I updated my /config/environments/development.rb file to have the following settings for ActionMailer and all was good!

config.action_mailer.server_settings = {
  :address => "127.0.0.1",
  :port => 25
}

 | 
Wednesday, June 13, 2007 2:38:32 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Saturday, June 09, 2007
As I stated a couple days ago, I was planning on learning MonoRail for a very small project that I'm working on.  Due to various circumstances, I'm not going to be using MonoRail, and will instead be learning a little more Ruby on Rails.  The primary issue is that I've been having a lot of problems as well as frustrations with Parallels lately.  The  biggest frustration is that I can't seem to get going within VS.NET due to OS X having all my common keyboard shortcuts mapped to other things.  I know I could remap them, but when I'm in OS X I want them to be mapped to the things they're supposed to.  The other issue is that VS.NET is repeatedly hanging, left and right.  I'm not sure if its a Parallels issue, or a problem with having both Orcas and VS 2005 installed or something else.  What I do know is that it makes trying to get anything done very difficult.  The final issue, which may be much more my own fault than anyone elses, is that getting going with Castle proved to take longer than I anticipated.  My primary issue was in trying to get everything built from the trunk with the VS.NET wizards and such setup.  I'm still getting a compile error that's related to AL.exe which may be related to having Orcas installed side by side with 2005.

Anyway, I've decided to go with Ruby on Rails instead.  Below are some things that I think are going to be of value:
By the time this project is over I should have a pretty good overall feel for Rails, and will be posting my thoughts on it in comparison to my primary development platform (.NET/C#). I'm going to continue to look into getting everything going with Castle and MonoRail as well, since my initial reactions to it after going through some of the getting started material and documentation was very positive.

Regarding the Parallels issue, I think I'm going to clean things up in my virtual machine, copy them over to someplace safe on the network and go back to using BootCamp.  While Coherence and such is nice, I simply can't be productive when running the applications that are important to me (VS.NET) within Parallels.  Since Parallels supports BootCamp, perhaps I'll still use Parallels from time to time to quickly switch between XP and OS X, but for the most part I think I'll be ditching Parallels.  Heck, maybe I'll just give up Windows all together, and become a Rails developer. :)

 |  | 
Sunday, June 10, 2007 12:57:39 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [9]  |  Trackback
 Thursday, June 07, 2007
Tonight I found out the hard way that prior to version 5, MySQL don't support using an aggregate in an ORDER BY clause.  Unfortunetly my web host is currently on 4.1.21-standard of MySQL while my development machine is running 5.0.27-standard.  The end result is that some pages within the Rails app that I'm working on are not working so well on my staging box at Site5 :(

I tried to find details online about when ordering by aggregates was added, however, I didn't have any luck so all I know is that it works in the version on my dev machine, but not on the version that my web host is running.

Update: For those interested the work around is to include the aggregate in the select list with an alias, and then order by the alias.  So instead of including the aggregate in the order by like so:

SELECT Column1, Column2, etc FROM MyTable LEFT OUTER JOIN MyJoinedTable on MyTable.Id = MyJoinedTable.OtherId ORDER BY COUNT(*)

You instead need to do something along the lines of:

SELECT Column1, Column2, etc, COUNT(*) Cnt FROM MyTable LEFT OUTER JOIN MyJoinedTable on MyTable.Id = MyJoinedTable.OtherId ORDER BY Cnt

And yes, I know the SQL here is completely contrived and might not be showing why the order by count is needed but that's not the point.  And for those wondering, as far as I can tell Rails doesn't exactly make it easy for  me to do what I need to do.  I can write all the SQL myself, but I was using find along with an :include to pull in an association, which means the necessary SQL isn't something I want to write if I don't have to.



 |  |  | 
Friday, June 08, 2007 1:59:56 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Friday, June 01, 2007
I've thought several times about trying to learn the basics required to build an OS X application.  In the past, this meant either going with Java or Objective-C, neither of which I have much experience with.  I've heard a couple people mention RubyCocoa in the last couple of months, but I never looked into it to see what it was all about.  Thanks to Peter Cooper, of Ruby Insider, I've been enlightened and now know that RubyCocoa's goal is to allow OS X applications to be built with Ruby, which in hindsight shouldn't have been very hard to figure out. Although I don't have the time at the moment, I'm certainly going to add a "checkout RubyCocoa" task to my "stack". 

Peter offers the following links:

Friday, June 01, 2007 10:21:19 PM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Wednesday, May 30, 2007
As I've mentioned serveral times lately I'm currently working on a Rails application.  Overall, I've really enjoyed the experience and I'm glad that I took the plunge into unknown territory.  For the most part I've been creating everything within my Rails application as resources.  For those who don't know, using resources within Rails is how cool people build Rails apps these days.  Creating a Rails app as a set of resources makes it so your app automagically has a set of RESTful services that can be consumed by the likes of ActiveResource. Up until know I've had things setup pretty simply, and as such have only had standalone resources.  Tonight I needed to add a nested resources and found this post on the topic very helpful

 | 
Thursday, May 31, 2007 3:13:44 AM (Eastern Daylight Time, UTC-04:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Sunday, April 15, 2007
Over the last week or so I've been following a thread of blog posts that outline some of the issues that Twitter is experiencing.  For those of unfamiliar, Twitter is a "microblogging" site written in Ruby on Rails.  Over the last month or so they've seen some very serious growth.  They're supposedly seeing over 11,000 request/sec which is putting a hurting on their servers.  In this interview, Alex Payne points out some limitations in Rails, most notably it's lack of built in support for talking to multiple databases, that are making it particularly hard for them to handle the increased load.  As a result, several individual have put together plugins to make working with multiple read only slave databases possible.