Friday, 21 September 2007

quarter-master

Continuing my series of "why isn't this in ruby already?", we have some date functions that allow us to add and display the current financial quarter. I have even overridden "strftime" to accept the symbol '%Q' to display the quarter.

class Time
  # save the original strftime so we can call it later
  alias original_strftime :strftime
  # overload strftime to accept '%Q' to display the quarter
  def strftime(format)
    format = format.gsub('%Q', "Q#{self.quarter.to_s}") if format
    self.original_strftime format
  end

  # create a utc time using the year and financial quarter
  def self.utc_fq(year, fq = 1)
    self.utc(year, self.quarter_to_month(fq))
  end
  # create a local time using the year and financial quarter
  def self.local_fq(year, fq = 1)
    self.local(year, self.quarter_to_month(fq))
  end

  # turns a financial quarter (1-4) into the first month of that quarter
  def self.quarter_to_month(fq)
    ((fq-1)  * 3) + 1
  end
  # turns a given month (1-12) into the financial quarter
  # (1=jan-mar, 2=apr-jun, 3=jul-sep, 4=oct-dec)
  def self.month_to_quarter(month)
    ((month - 1) / 3) + 1
  end

  # returns the financial quarter of this date
  # (1=jan-mar, 2=apr-jun, 3=jul-sep, 4=oct-dec)
  def quarter
    self.class.month_to_quarter(self.month)
  end
end

Example of use:

>> order_fq = Time.utc_fq(order.created_at.year, order.created_at.quarter)
=> Sun Jul 01 00:00:00 UTC 2007
>> p "Order's financial quarter: #{order_fq.strftime("%Y-%Q")}"
"Order's financial quarter: 2007-Q3"
=> nil

Wednesday, 19 September 2007

methods in_time

On the subject of "why isn't this in Ruby already?". I've written up a set of conversion methods that I felt sure were there already, except that I couldn't find them anywhere.

class Numeric
  # assumes i am expressed in seconds - converts me to minutes
  def in_minutes
    self / 60
  end
  # assumes i am expressed in seconds - converts me to hours
  def in_hours
    self / 3600
  end
  # assumes i am expressed in seconds - converts me to days
  def in_days
    self / (3600 * 24)
  end
end

So now I can do things like: 3600.in_hours, but also the more useful: (prevTime - Time.now).in_days

Monday, 17 September 2007

float precision

So, I want to test that some floating-point helper function returns a certain value - but I only want it to check to a certain precision (so I don't get hit with negligible rounding errors).

Add this to config/environment.rb (and why doesn't this already exist in Ruby?)

class Float
  def precision(pre)
    mult = 10 ** pre
    (self * mult).round.to_f / mult
  end
end

Then you can do things like this:

assert_equal -5087.35, order1.profit_loss.precision(2)

[Edit: I've replaced 'truncate' with 'round' - it's the only change I've made in two years and I'm still using this code... maybe I should put it into the Rails core-extensions instead?]

Monday, 27 August 2007

Truth in Fiction

So, I was having dinner with my cousin the other day[1]. Now my cousin and I are both part of an international book-swapping club, so we often swap books with each other, or chat about the books we're currently reading. Anyway, she had a book to lend me, and gave me a brief description of what it was about and why she liked it. What struck me was her use of the word "inoffensive" as a descriptive for the plot.

Now, I like to think I don't really judge a person by their book-taste. I mean everyone's different, and that's just fine. If you want to waste your time reading endless soppy romances, or brain-dead action books with no plot, but lots of sex... that's not my choice and doesn't impinge on my life one jot, so go for your life.

But it got me thinking about what it is that I *do* look for in a book. After all, my taste is, you could say "highly eclectic". I have fiction, non-fiction, fantasy, mysteries, science-fiction, speculative fiction, historical fabrications, and even the odd romance or action book.

With all that diversity, is it possible for there to be an overall theme running through here? Clearly not in genre, but the contrast with the word "inoffensive" really got me thinking.

I don't care if a book is offensive, what I value in a book is its sense of Truth.

Now, clearly I don't mean "it must be a true story" - after all, I read a hell of a lot of fiction (about 40-60 books a year on average). I also don't mean "it must mirror reality" as I read very little mainstream (the realm of "near reality" books) by comparison with my science fiction and fantasy.

After all, "The Lord of the Rings" has elves, and orcs and and magic rings galore, so you couldn't call is a true story, but in one sense it is a True Story. It thoroughly explores the reactions and relationships between the characters, and thereby delves into the Truth by exploring how to hold onto friendship through a struggle against near-overwhelming odds. About the Truth of courage, how it doesn't mean you are unafraid, but that you are prepared to struggle on for a cause that is worth fighting for, even when you are certain that you will not see the end of it.

It is this kind of Truth that I value in (what I consider to be) a good book.

Once I got onto that train of thought, I also realised why some other books really didn't appeal to me. I've recently tried to read my way through a few of the classic "Stainless Steel Rat" stories (by Harry Harrison). Mainly because several SF-fan friends of mine (mainly male) have enthused about how they loved them as kids. When I came to read them I found them to be bog-standard "boy's own adventure" stories... just set in space. Which were *so* not to my taste.

In the light of my new discovery I can see what was lacking in them that turned me off. A boy's own adventure works like a fantasy/day-dream. Everything goes just perfectly. Even when things are going wrong, you know that some Deus ex Machina is waiting in the wings to save the day. I get the same feeling from Traci Harding (though that is fantasy of the female kind).

Some authors bounce between the two ends. Laurell K Hamilton can push too far to the fantasy side of things, her recent books have this side clearly overshadowing the plot. Whereas her earlier books showed a great ability to get to the Truth of the relationships between the characters. Her main character (Anita Blake) is a vampire-hunter, hunting rogue vampires in a world where vampires have been made into "legitimate citizens". Unfortunately, vampires have several "natural" abilities that can cause problems in humans (especially those creating an irresistable "draw" or desire). Laurell writes poignantly about Anita's internal emotional struggle against the desire she feels for a particular vampire while simultaneously having to deal with the physical struggles she goes through in the course of her job.

Of course this also aparrently involves a lot of sex...

So, to get back to the original point, I wonder a bit about what my cousin meant by describing a book as "inoffensive". Inoffensive to what?

I can only guess that she meant inoffensive to her Christian values, and to her sense of well-being. Like many people, she probably doesn't want a provocative book that jolts her out of her current orbit. This is reasonable. She's a mother and definitely has a lot on her plate already... but this kind of thought-provoking, stimulating book is exactly what I crave.

So, I don't hold out a lot of faith that I'll really find her book to be as interesting as she finds it. But I'll definitely give it a go. Who knows? Maybe I'll be pleasantly surprised.

Notes

[1]Surjit's Indian Restaurant: 215 Parramatta Road Annandale (Sydney). I thoroughly recommend this place - they do fantastic Indian. Aparrently the Sri Lankan cricket team visits there when they are over here.

Thursday, 9 August 2007

validates percentage

So, we wanted to check that a user could enter both "20" and "20%" and "20.000%" and have them all perfectly valid for a field on our models. I finished up with this validation method (below) to add to ActiveRecord::Base.

  # validates whether the given object is a percentage
  # Can also take optional args which will get passed verbatim into the
  # "validates inclusion" method.
  # It will safely take the usual set of fields for that - but if you pass
  # in a new message - it will get used for both validations.
  # The default message is: "should be a percentage (0-100)"
  def self.validates_percentage(fields, args = {})
    msg = args[:message] || "should be a percentage (0-100)"
    validates_each fields do |model, attr, val|
       pre_val = model.send("#{attr}_before_type_cast".to_sym)
       unless val.nil? || !pre_val.is_a?(String) || pre_val =~ /^[-+]?\d+(\.\d*)?%?$/
         model.errors.add(attr, msg) 
       end
     end
    args[:message] = msg
    args[:in] = 0..100 
    validates_inclusion_of fields, args 
  end

Friday, 13 July 2007

Assert no errors

Small snippet today... I've mainly been working on updating the test-coverage for our app the last couple of weeks - so nothing particularly useful to share. I have, however, found the following tiny test-helper method to be useful.

Many tests require you to check for a particular error on a specific field on an object... but you also tend to check (over, and over, and over) that there aren't any errors on a given object. So I extracted that out.

Put this into "test_helper.rb" for increased DRYness

  # Assert that the handed object (thing) has no errors on it.
  def assert_no_errors(thing)
    fail("should have passed an object") unless thing
    e = thing.errors.full_messages
    assert e.empty?, "Should not have error: #{e.to_sentence}"
  end

Tuesday, 19 June 2007

Slice and Dice

I've been playing around with sorting and scoping to neatly and easily sort and filter an index page. I'm finally happy with a generic set of scoping/sorting methods I can quickly apply to a new resource. It uses the autoscope plugin I discussed earlier, as well as the smart column sorting I played with.

Scope up

To start with, drop some scoping into your model object - and add the three required methods below (with suitably appropriate modifications for your purposes).

  auto_scope \
       :active => {:find => {:conditions => ['destroyed_at IS NULL']}},
       :archived => {:find => {:conditions => ['destroyed_at IS NOT NULL']}}

  # Available scopes - shouldn't this be available via autoscope?
  def self.scopes
    [:all, :active, :archived]
  end
  # Defaults (put into the model object)
  def self.default_scope
    :active
  end
  def self.default_sort
    '(destroyed_at IS NULL) DESC, login ASC'
  end

Next, drop these methods into your application.rb

  # Generate a quick-and-dirty description of the chosen sort order (for displaying in the template)
  def sort_desc
    "#{params[:dir] == 'down' ? 'descending' : ''} by #{params[:col_name] || params[:col]}"
  end
  # Generates a SQL order-by snippet based on requested sort criteria (or given default). 
  #
  # Adapted from the following blog post:
  # http://garbageburrito.com/blog/entry/447/rails-super-cool-simple-column-sorting
  def sort_order(model, default)
    orderby = "#{params[:col]} #{params[:dir] == 'down' ? 'DESC' : 'ASC'}"
    return sort_desc, orderby
  end

  # Uses model scoping to generate a scoped subset of the required objects
  # for use in the index view.
  # Returns a sorted list of the object .
  # Assumes existance of three methods on the model: 
  # scopes:: returns an array of acceptable scopes for this model
  # default_scope:: returns the scope to use when none has been selected
  # default_sort:: represents an SQL-appropriate string for this model
  #   representing the default way of sorting this model object
  def scoped_search(model, scope)
    scope = model.default_scope unless model.scopes.include?(scope.to_sym)
    sort_desc, orderby = sort_order(model, model.default_sort)
    # a description of the search/sort to display in the view
    filter_desc = "#{scope.to_s} #{model.name.pluralize.downcase} #{sort_desc}"
    return filter_desc, model.find(:all, :order => orderby) if scope.to_sym == :all
    return filter_desc, model.send(scope.to_sym).find(:all, :order => orderby)
  end

Using it is now easy. Drop something like this into your controller and call on it for all your collection-based actions.

  # applies user-specified filters and sorting to the specified collection
  def filter_users
    scope = params[:user_scope].to_sym if params[:user_scope]
    @filter_desc, @users = scoped_search(User,scope)
  end

If you need to paginate, you can always paginate-collection, or add the code into the scoped_search function.

Tuesday, 12 June 2007

Super Cool Smart Column Sorting

So, I wanted to drop in some basic column sorting without having to rip out the innards of something like streamlined. I googled and came across this blogpost on SCSCS - which is so worth it for super-cool simple column sorting...

But I'm just not satisfied by what it can do. As ever, I want more. In this example, I wanted to be able to display neato little up/down arrow widgety thingies on the column heads by giving the th the appropriate "up/down" class - so the user can see which column it's all sorting by.

Arrowy goodness

We want a way to stuff a CSS class into the table's column-heads so we can show the sorty arrows. We need to indicate two things. Firstly, when the data has been sorted by a particular column, we want to indicate "this is the current sort colum". Secondly, we want to be able to indicate the sorting direction of a column (up, down or indifferent).

So the first step is to create (or appropriate) arrow-images. I'm not going to show an example here (you can figure that out for yourself) but I'll assume you have three images: SortUp.gif, SortDown.gif (to show that the current column is sorted up or down), and SortAny.gif (a double-arrow to indicate that the column could be sorted if they want to).

Stylish stuff

Then you need to put something appropriate in your stylesheet. eg:

/* what an ordinary column-head looks like */
.dataTable th {
   background-color: grey;
   color: white;
   padding-left: 15px;
   padding-right: 4px;
}
/* colour for currently sorted column */
.dataTable th.current {
  background-color: black;
  color: white;
}
/* the sorting link */
.dataTable th a {
  color: white;
  text-decoration: none;
  display: block;
  width: 100%;
}
.dataTable th.current a {
  color: grey;
}
/* pretty colours when hovering */
.dataTable th a:hover {
  color: blue;
  background-color: grey;
}
.dataTable th:hover {
  background-color: grey;
}

/* display of up and down arrows for sortable columns */
.dataTable th.up {
  background-image: url("/images/SortUp.gif");
  background-repeat: no-repeat;
  background-position: center left;
}
.dataTable th.down {
  background-image: url("/images/SortDown.gif");
  background-repeat: no-repeat;
  background-position: center left;
}
/* display for "any" sort - eg up and down arrows */
.dataTable th.any {
  background-image: url("/images/SortAny.gif");
  background-repeat: no-repeat;
  background-position: center left;
}

Stuff to note:

  • The "current" column head is a distinctively different colour to a normal column - this makes it stand out.
  • The "hover" colours provide good feedback for users - they pick up the idea that clicking here will probably do something.
  • The anchor within the column head has display:block; and width:100%; this makes the anchor stretch to the full width of the column-head - which is nicer than having to click just the word itself.
  • There's a padding-left on the anchor columns - this gives room for the arrow images. I've specified 15px as it's big enough for the images I use - YMMV.

Classy heads

So now we need to adapt the sort_link method to make it actually use this stuff. But we don't want it just on the link - the class needs to go on the whole column-head. So write a wrapper-function that will generate the whole <th> for you (class and all):

  # generate appropriate class for current sort options
  def sortlink_class(col)
    return "any" unless params[:col] || params[:dir]
    return "current #{params[:dir] == 'up' ? 'up' : 'down'}" if params[:col] == col.to_s
    "any"
  end

  # Generates a column head tag that contains a sort link and is given the
  # appropriate class for the current sorting options.
  def column_sort_link(title, column, options = {})
    content_tag 'th', sort_link(title, column, options), 
                      :class => sortlink_class(column)
  end

  def sort_link(title, column, options = {})
    if options.has_key?(:unless)
      condition = options[:unless] 
      options.delete(:unless)
    end
    new_sort_dir = params[:dir] ==  'down' ? 'up' : 'down'
    link_to_unless condition, title, request.parameters.merge(options.merge(:col => column, :dir => new_sort_dir))
  end

So, the currently sorted column will get something like class="current up", wheras most of the columns will be class="any". You'll also note I updated the badly-named "d" and "c" to "dir" and "col" so that unsuspecting maintenance people might have a clue as to the actual purpose of the options. Self-documenting code being a Good Thing.

Finally, I've modified it to pass through any extra options to the controller by merging the options into the link. This can be used to pass through requests for special sorts, extra parameters etc.

Friday, 8 June 2007

Sliding Door Tabs take 2

So, a while back I wrote a quick widget for making sliding door tabs. But it wasn't enough, I wanted *MORE*. I wanted them to be responsive to conditions.

For example, I have a resource User, and I want the "users" tab to stay open no matter which user page I'm on (index, show, edit etc)... *unless*, of course, it happens also to be the "my account" page (ie I'm viewing myself)... for which I already have a tab. This is a cut above just being "on" if we happen to perfectly match the current url.

So I rewrote the helper methods. Now my tabs come with optional separators (that can be independantly styled), and with the ability to pass in a conditional to override whether or not to show the tab as "on".

  def make_tab(t)
    # use the conditional if one was passed - default to current page 
    cond = t.has_key?(:cond) ? t[:cond] : current_page?(t[:options])
    content_tag "li", link_to(t[:name], url_for(t[:options])),
                             :class => (cond ? 'current' : nil)
  end

  # Builds a tab that is just a separator
  def make_separator
    "<li class='separator'></li>"
  end

  # Make tablist out of a given set of tabs.
  def build_tablist(tabs, do_sep = true)
    list = "<ul>"
    tabs.each_with_index do |t,i|
      list << make_tab(t)
      list << make_separator if do_sep && i != tabs.size - 1
    end
    list << "</ul>"
    list
  end

And an example of use (that assumes existance of restful_auth)

<div id="topnav" class="tabNav">

    <% # standard set of tabs
      tabs = [] 
      if logged_in?
        tabs << {:name => 'dashboard', :options => dashboard_url}
        tabs << {:name => "my account", :options => user_path(current_user)}
        if current_user.is_admin?
          tabs << {:name => "widgets", :options => widgets_path, 
            :cond => (current_controller?(hash_for_widgets_path))}
          tabs << {:name => "users", :options => users_path, 
            :cond => (current_controller?(hash_for_users_path) && 
                      !current_page?(user_path(current_user)))}
        end
        tabs << {:name => 'logout', :options => logout_url}
      else
        tabs << {:name => 'login', :options => login_url}
        tabs << {:name => 'forgot password', :options => forgot_password_url}
      end
-%>
      
  <!-- tabbed browsing of main site areas --> 
  <%= build_tablist tabs, false -%>
</div>

Note that it also uses a convenience function: "current_controller?" This is below and could almost certainly be done better... but it currently serves to check if the given url-options match the current controller.

  # determines if the given set of options contains the current controller
  def current_controller?(options)
    return true if current_page?(options) # trivial case
    if options.respond_to?(:has_key?) && options.has_key?(:controller)
      return options[:controller] == controller.controller_name
    end
    # try matching it - assumes it's a string url
    options =~ /#{controller.controller_name}/
  end

Friday, 25 May 2007

Scope out your models

Just found a nitfy plugin called AutoScope. It lets you define scopes for a model. For example:

class User < ActiveRecord::Base
   auto_scope \
       :fresh => {:find => {:conditions => ['activated_at IS NULL AND destroyed_at IS NULL']},
       :active => {:find => {:conditions => ['activated_at IS NOT NULL AND destroyed_at IS NULL']}},
       :archived => {:find => {:conditions => ['destroyed_at IS NOT NULL']}}
end

These set up some scoped methods

 new_count = User.fresh.count
 old_users = User.archived.find(:all)
 User.fresh.find(:all).each {|u| u.update_attribute(:activated_at, Time.now.to_utc)} 

I've found these great for filtering collection views that group users distinctly, but span across multiple columns.


    def filter_users
      return default_search unless params[:user_scope]
      scope = params[:user_scope].to_sym 
      case scope
      when :fresh, :active, :archived
        # scopes we recognise
        users = User.send(scope).find(:all)
      else
        users = User.find(:all)
      end
      users
    end

Do note, though, to be careful what to name your scopes. I started out by calling my "fresh" scope "new". Unfortunately this overwrote the "new" function on my User model... not a Good Thing.

Tuesday, 22 May 2007

Don't flash your partials!

Random Rails tip #1: Don't use a partial named "flash" (well: "_flash.rhtml" to be specific) if you don't want to be flooded with deprecation warnings.

Rails auto-magically creates an instance of @flash for you. This triggers an avalanche of warnings for you in your functional tests :P

Tuesday, 15 May 2007

RubyFit that works...

We're setting up a FITnesse server and intend to use RubyFIT for it. I tried using Cory Foy's tutorial to help get them talking to each other - but found it was out of date. The differences:

  • Get your Rubyfit from sudo gem install fit instead of "grabbing ruby.zip" (because ruby.zip no longer exists on the Interweb)
  • Instead of !define COMMAND_PATTERN {ruby -I %p ruby/bin/FitServer.rb -v} use !define COMMAND_PATTERN {ruby -I %p <path to your fit gem's bin>/FitServer.rb -v}
  • ignore the fact that FITnesse seems not to be as verbose with reporting the details of exceptions as Cory Foy's tutorial suggests - just move on to the "path" step

Sunday, 13 May 2007

Exuberant programming

My colleague (Peter Merel) is the sort of person to get enthused at trying new stuff out. He is an Agile-evangelist, and has been trying all different ways to make this process fit into corporate-land. The main issues involved in this tend to be getting buy-in from the usual management-types who have never been exposed to this methodology, and finding ways to interpret it into the sorts of controls and reporting guidelines that they are used to.

Don't blow up the universe

The kind of "No, no! everything you're doing is wrong, get rid of it all and work our way!" approach tends to be frowned-upon as disruptive to standard operating practice. For good reason - it is.

Changing over an entire system of business practice (such as how to develop software) is a Big Thing for any company. Techie types will often scoff and refer to the inertia of corporate behemoths, entrenched dinosaurism and a corresponding lack of corporate flexibility, but the managers at these places actually have a good point. Changing systems involves time, effort and risk of failure (whether total failure of the system or simply setbacks that cause loss of market share).

A bigger company has more systems and people involved - and so more chance of breaking something valuable. They will generally have an entrenched and provably working system of practice. It may not be the best that is out there, but it has gotten them to where they are now. It's up to you to prove to them that what you're offering is not only better, but that it's worth more than the pain and effort involved in changing over.

Managerese

A complete re-write of corporate practice tends only to come onto the books once the proverbial hits the fan. At which point the company is desperately flailing around for any lifeline they can reach. But most companies actually aren't in this position, which means you have to actually, you know, convince them that what you're doing is a good idea (wierd huh?).

This requires an ability sadly lacking in most techie-types... the ability to speak with management in their own language.

There are a number of supporting tools that assist managers to get a handle on a project - tools they are used to and understand. The requirements spec, the gantt chart, todo lists and regular meetings. They not only understand thse, but know how to integrate them into a working whole. They use them to to juggle tasks and developers, to track project progress and momentum and to basically Get Things Done.

If suddenly you arrive on the scene like some animated furry-toothed geek enthusing wildly about "user stories" and index cards and stand-up meetings; sneering at the locals with their endless requirements specs, gantt charts and deliverables; refusing to work with management unless they change all their habits to match your own... you'll undoubtedly gather some resistance to your methodology ideas... even if they would be better off in the long run.

Bridging Mount Learning-curve

So what can you do to bridge the gap? Is there a way to implement all of our agile programming practices, yet still present the incumbents with the tools they are used to seeing? Can we apply the Principle of Least Surprise to our stakeholders too? Can both worlds co-exist in joyful harmony?

This is what we're currently working on. We call it "exuberant programming". It's a set of tools that allows us to be "abundantly fruitful" with our productivity (using the latest in agile methodology), while still giving joy to the more traditional managers.

The project managers are already productive and don't have the time to scale Mount Learning-curve. So let them have their requirements specs, but instruct them how to structure them using user stories, with each sentence a function point that can be fed into the priority planning-game. Let them have their Gantt charts - but use them to show User Stories. Update them at the stand-up-meetings and generate burn-down charts for the managers to let them see the project velocity.

We can work together. We can have peace in our time! We are the world... <waves lighter in air>

er, sorry, got a bit carried away there...

You can see the potential of what we're proposing. We're still working on the details. I'll post more about it as we develop it.

Saturday, 28 April 2007

Exploding contracts == dilemma

Two weeks ago I was bemoaning the fact that my cash flow was in the red and my savings were running away in a torrent. I was then approached by a friend for a contract. Shortly after my interview with them I had four other clients approach me. So suddenly I'm flooded with offers!

One of the other clients was a good friend of mine as well. So I had a real dilemma on my hands. I didn't want to disappoint either one.

The first contract came first - but they hesitated on giving me a "Yes definitely" answer until after I'd started to look at the second one. I felt I had to look at each of them in good faith.

The first contract offered sexy video on the web, the second a really big name financial company

The first contract offerred a relaxed, sociable startup feel with some onsite some offsite. The second offered relaxed, sociable academic feel, onsite-only, but I'd have the chance to teach the rest of the team Rails skills.

It was pretty much neck-and-neck. It was a tough decision, from the perspective of preserving friendships. But when I weighed all the pros and cons objectively, the business decision became clear. In the end, for me, it came down to the fact that the first contract could only offer three days a week, while the second offered full-time.

I start on Tuesday.

Tuesday, 24 April 2007

Presenting Rails

Ok, so this post was going to be how I gave an absolutely rocking presentation on Rails to my local LUG group (SLUG).

Unfortunately, I was giving the second talk and the first one began late and then ran way over-time. So my talk was pre-empted. The SLUG team were really nice about it (they even bought me dinner), and I'll be running it next month instead.

I certainly can't fault them - the first talk was on the cool OLPC project. I was interested in listening myself. Besides which, an extra month will give me more time to polish the talk and prepare that demo I'd meant to organise...

Anyway, I did want to mention a really cool talk I stumbled over while researching other Introductory Rails talks. Jim Weirich gave this talk and has a lot of reference material available here, but what I wanted to point out the neat slide software he used.

It's called "The Takahashi method" and is a XUL file that runs in your browser. It lets you write simple and effective slides with an image or a few words on each. These give great impact to what you're trying to say.

The data file for the slides is simple plain-text markup, so it's ultra-quick to write up your slides from your presentation notes.

Here is a link to Jim's slides and data. See how punchy that is.

Anyway, that's what I would have used... if I had the chance ;)

Friday, 20 April 2007

Coding through treacle

Coding while sick is like trying to walk through fairy-floss

I once tried to explain to my aunt (a respected Dietitian) about how you need your whole brain firing on overdrive to write truly awesome code... it was difficult to explain clearly and I didn't pull it off successfully. Apparently I left her with the feeling of "and you don't think I use my brain in my work?" which was *so* not the point I was trying to make.

In my experience, most jobs (ie non knowledge-work jobs) have an element of drudgery. Tasks that you can do with only half your brain involved. You might not be able to do them while sitting in front of the tv - or while chatting with a friend... but you can do them when you're feeling less than 100%.

Coding isn't like that. Neither are things like mathematics, theoretical physics and creative writing.

At least 95% of the tasks you do require full attention. It's not like you suddenly forget how to code (or write, or whatever), it's just that if you do that work when you're not "all there"... it'll be far more buggy and inelegant. You might be able to salvage most of it, maybe with only a bit of re-writing, but if you're seriously out of it, you'll have to re-write so much of it that you might as well write it from scratch... ie you'd be better off having not written it at all.

The last week and a half has been like that for me. I've been trying to see through a near-impenetrable fug of virus-induced head-cold.

I've watched a lot of television. I've made significant in-roads into my post-easter chocolate collection. I even began a new knitting project... but I haven't coded much.

I even had trouble concentrating enough to get through my email. When you find yourself blankly staring at the screen, and realise that you've been sitting there, doped out for ten minutes doing nothing... you know there's no point firing up the text-editor.

Still, the fog has begun to clear over the last few days, so I'm slowly picking up where I left off. Which is lucky as I'm helping a friend out - he's sub-contracted a few basic rails tasks to me on his current project. Hopefully I'll be back in full-gear next week as I have a contract-interview and a talk on Rails for my local LUG.

Tuesday, 3 April 2007

Plugins and engines and gems, oh my!

So I was talking to friend of mine about what I was doing and how a gem was too heavy for what I wanted. He pointed out that I should consider doing it as an engine instead of a plugin.

What's the difference between a plugin and an engine you ask?

I didn't know either... engines seem to be the forgotten children of Rails in all the current plugin-love that's going around (not knocking it - I like plugins too).

Anyway, it turns out that an engine is a plugin - with some differences. An engine requires that you install the "engines" plugin first - you can't just script/install the plugin itself. However, adding that engines plugin allows your own baby to do a hell of a lot more than your standard plugin-ly functions.

An engine is a complete, vertical slice of MVC. An ordinary plugin, by comparison, is generally a small chunk of functionality such as a helper library. Engines can have an /app/ directory structure identical to a full rails site. You can also add routes and migrations (with some user-tweaking required). This allows a fully encapsulated chunk of functionality (such as what I was proposing for my little blog).

Now, mephisto and typo are both gems. This is because they contain a huge amount of functionality (they well deserve their leading status in the Rails-blog field). They contain more functionality than what most people associate with a simple plugin... more than what people would associate with an engine (if people used engines more commonly) - so they are distributed as gems.

So, to sum up:

  • plugins are for small bundles of helpful code
  • engines are for encapsulated slices of vertical functionality and
  • gems are for complex, multi-functional systems.

So how do I make an engine?

The information on how to make an engine is a bit scattered about the web. There doesn't seem to be a whole lot out there in the way of tutorials (at least not compared to plugins).

Some of the info seems to be downright incorrect. The article that looked most promising was: the alterthoughts one, but it seems to be based on an old version of engine-construction that Just Doesn't Work. I couldn't get script/generate engine my_blog to give me anything but "can't find a generator for engine". This article is clearly built on an earlier version of both Rails and engines

The railsdoc on engines is fairly complete (though it's not a step-by-step tutorial). It turns out that you can just start out with a rails app - and turn it into an engine. Two things to remember:

Routes
Copy your engine's routes.rb into the root directory. Then instruct your users to add map.from_plugin :your_plugin into their routes.rb.
Migrations
If you have migrations, make sure they are numbered from 001. Then leave instructions for your user to run script/generate plugin_migration, then rake db:migrate.
Shared plugins
A blog needs to share the authentication plugin. But which authentication mechanism are you using? I could assume you're using the same as me (RESTful auth right?) but that's not likely. The best option is to write a wrapper library that allows people to override the functions with their own authentication system, if they choose.
Other plugins
If your plugin depends on other plugins there may be some duplication. I'm sure there must be a way that minimises double-loading of plugins eg if your plugin uses acts_as_taggable, and so does their site - maybe your install.rb could check for that and not bother installing it - but I think that may be over-optimisation.

I'm sure there must be a way to put all these tasks into "install.rb" - but I haven't had a chance to do that yet.

So, what have you done?

So I wrote a very tiny blog app (currently all is does are posts). It was enough to demonstrate the point for me while I figure out how to do the engine thing. I'm still playing with it in my spare time - but I probably won't get in installed until after the Easter long-weekend. At that point I'll also find somewhere to upload it so people can have a play with it.

Friday, 30 March 2007

A blog to call my own

So, I've been thinking about shifting my blog over to my homepage recently. Why? well blogger's great, but I really need to move out and find a blog of my own. I want a tighter control over the content, I want to integrate it with my website's styling and layout and maintaining it in two places violates the DRY principle...

Ok, so I'm lazy and don't want to have to maintain stylesheets/layouts in two places :P

So anyway, in Rails, the major blog movers-and-shakers atm are Mephisto and Typo. They're both great. They provide heaps of functionality and have a thriving developer community. But they're a little on the top-heavy side. All the bells an whistles, Mephisto is almost a full CMS... you have to pretty much install either one as a new app (or hack it a lot ot fit with your existing one).

This is great if:

  1. you're starting an entirely new website from scratch
  2. you like using a CMS-approach to organise your site for you
  3. you're ok with your blog being a completely independant rails app.

In my case:

  1. I already have a pre-existing website. It might not be much, but I like what I've done and I don't want to have to re-hack it to fit around my blog software. Conversely, I don't want to spend hours hacking my blog software to fit in with my website - and risk destabilising the upgrade path (which kinda defeats the purpose).
  2. I'm a rails freelancer - not a stay-at-home mum. I like to get my hands dirty in the innards of my site. I don't like having the structure of said site dictated to me by some upstart CMS (no matter how shiny). I like to call the shots on my own turf
  3. We're seriously violating the DRY principle here. Why on earth would I want to maintain two separate sets of layout/styling? or two separate authentication systems? Single sign-on is a PITA. Yes, there are solutions, but why invite the problem into your home? and you couldn't integrate the layouts (eg put your latest post on the homepage) without contortions. No RESTful articles_path for you!

What I really want is to be able to do something like
script/plugin install blog
and have it all Just Work(tm). That doesn't seem available anywhere.

So, I've decided to write my own.

It won't be anything flash, just something bog-simple to allow me to post articles, tag them, let people comment and generate an RSS feed. It won't have whizz-bang flickr integration (well, probably not), but it's all that most people seem to need.

I'll post updates here as I progress.

Tuesday, 27 March 2007

No to death threats!

I am shocked and horrified. By this post outlining sexually explicit death threats levelled against Kathy Sierra. This behaviour is outrageous and should not be tolerated. Kathy is a wonderful person, an excellent speaker and a giving member of the tech community. She has my full support. My thoughts and best wishes go out to her as she copes with her current situation.

Let's not let it happen again. If you notice such unruly behaviour forming in your own blog/forum/community - head it off. Inform the person that this behaviour is not appropriate. If that doesn't work - then do something more drastic (ban them from the site and call the police).

[Update: Andy Carvin has posted (on "stop cyber bullying day") a social network he has set up to help people combat cyber-bullying here.]

Sunday, 25 March 2007

Social overload

So, just how many Rails social sites are out there? Seems everyone and his dog is in the process of creating a new one. I suppose this shouldn't be really surprising given how deeply entwined Rails is with the "Web 2.0 revolution"... but still.

Here is a shortlist of my current profiles:

Working With Rails
By far the best of the lot. It seems to have been around the longest - and if you're not on it, you're not anybody. This is the site that features the luminaries of the Ruby and Rails world. It also seems to be in active upgrade mode atm. They've just added a whole bunch more features.
Network of Ruby Freelancers
You can't access this site without registering. The concept is that this site marrys up freelancers with firms looking to hire. It's still a bit rough-and-ready, but it's only really just been launched. Still, there are already over 50 freelancers listing on it. They also cater for sub-contracting, allowing you to quote your sub-contract rate so other freelancers can pass their work on if they're overloaded.
Rails for all
I find this site to be way too complicated. I really like the navigation options (something that WWR is missing), but once you start trying to get to actual data, things aren't intuitive. It's also not as stable as it could be (the search fell over for no reason). There's a lot of potential here, but I think the developers tried to swallow too much at once. It has about the same level of functionality as WWR, but is far less dependable.
Freelancers on rails
Not a social-site per se, but a google-group intended for conversations about freelance rails contracting. Mentoring, tips and experiences. The members are pretty helpful and the topics cover a wide range of issues within freelancing. Worth joining if you're a freelancer.
Technorati
Ok, so this definitely isn't a rails-specific social site, but there are a lot of rails-specific blogs available here. I probably don't need to say more.