has_wiki_field: quickly building a wiki in Ruby on Rails

Posted on December 16th, 2007 in Nerdy,ruby,ruby on rails by toholio

Has the boss just discovered wikis? Does he now want to be able to create links between records in your intranet applications? Need to quickly add wiki functionality to your models and views so you can get back on with your life?

That’s what happened to me recently. Since the wiki code was almost exactly the same for all of the applications that needed changing, I’ve put the code into a plugin. Hopefully someone else will find it useful.

Installing the plugin

The plugin is installed in the same manner as any other. Fire up your favourite terminal and navigate to the root of your rails application. Then run the following command:

script/plugin install http://hazy.stupor.org/svn/has_wiki_field/trunk/has_wiki_field/

That should be all that is required.

Using the plugin

The following example should get you up and running quickly but make sure you read the efficiency note below.

Lets say you have a Person model that has name and bio attributes. We would like to be able to link to other people from within a bio. So in Allan’s record we might want the bio to read “This man is friends with [[Betty]]” and have [[Betty]] automatically change into a link to her record when it is displayed.

We, start by adding has_wiki_field to the Person model:

class Person < ActiveRecord::Base
  has_wiki_field :field => "name", :sql_match => "LIKE"
end

The :field option specifies what field should be matched by the text in [[links]]. The :sql_match option specifies how the records should be matched. :sql_match defaults to “=” but using “LIKE” will allow case insensitive links.

Now we need to change show.html.erb for the people controller so that links are generated from the bio.

Where previously we might have displayed a bio using:

<%= h @person.bio %>

We will now use the wikify method, passing it the name of the attribute to wikify and a code block which generates the html for links. A code block is used to allow flexibility in link generation. The following block simply calls link_to but you could, for example, write a block which looks up an image associated with your model and displays that instead.

Anyway, for our Person model we add the following to the view:

<%= @person.wikify(:bio) do |name, object|
    if object.nil?
      h name
    else
      link_to name, object
    end
  end
%>

In a real application this should be put into a method in people_helper to help keep things tidy.

That’s it! Where [[Some Name]] appears in a Person’s bio it will be turned into a link to the person with the name ‘Some Name’.

Remember to read the important efficiency note section below before using this in a production environment.

An important note about efficiency

The default method used for finding which object a [[link]] points to is not efficient. For sites that receive more than a tiny amount of traffic it should be replaced by your own model specific method.

The default method takes the contents of each [[link]] and queries the database for the first record that has ‘link’ as the value for the field specified in the model, I.e.

find(:first, :conditions => ["somefieldname = ?", key])

This will obviously require a database look-up for every link which could slow your site down tremendously for pages containing many links.

To fix this you must provide your own method to match objects with the keys extracted from [[links]]. The class method to override for this is object_for_key(key).

For example, if we have a class called Person we might replace the object_for_key method like so:

class Person < ActiveRecord::Base
  has_wiki_field
 
  def self.object_for_key( key )
    # some super fast method for matching the key
    # from a link to a person object, goes here...
    #
    # return the Person object that matches or nil if there is no match
  end
end

Naturally, it’s up to you to manage the data used by your object_for_key method. wiki_options[:field] and wiki_options[:sql_match] will be available to you in this method if they were set as options to has_wiki_field.

Future plans

The plugin doesn’t do much currently. If I’d only needed it for a single application there’s a good chance it wouldn’t have made it into a plugin at all. It has provided me with a reasonable starting point for my applications and hopefully it’ll get better as time goes on.

Some ideas for future versions:

  • Add a controller action which takes a key and redirects to the appropriate record or creates a new record with the needed field already filled.
  • Using the new controller method above, allow links of the form [[Some Key#Model]] where “Model” specifies what type of thing links are pointing to. Ta-dah! Now we can link between all the models in an application.
  • Implement some basic object_for_key methods for common situations. The plugin should attempt to gently direct programers towards these methods.
  • Implement a basic link caching mechanism. When a has_wiki_field model is saved links should be extracted and stored in a table. Then all current links for a model can be loaded in a single database transaction.

Generating an iCalendar feed from a controller in Ruby on Rails

Posted on December 11th, 2007 in Nerdy,ruby,ruby on rails by toholio

Recently I needed to set-up an application to keep track of regular safety inspections for power tools and other equipment. The application is very trivial but my client was quite pleased with one particular feature which wasn’t actually requested.

The “bonus” feature was an iCalendar feed which allows the client to have his computers subscribe to the feed and keep up to date with what equipment needs inspecting and when. Very swish and, thanks to Rails and a nice gem, very easy.

So how’s it done? Easy!

Lets start by installing the icalendar gem. Open a terminal and install it as normal:

user@host railsapp$ gem install icalendar

Change to the vendor directory of your Rails application and unpack the gem:

user@host railsapp$ cd vendor/
user@host vendor$ gem unpack icalendar

Make sure it will be loaded by adding it to the end of config/environment.rb in your Rails application:

require 'icalendar-1.0.2/lib/icalendar'

Now we’re ready to add a calendar feed to our application. Lets say we have a table that contains the names and scheduled service dates of some tools. The client wants, or is going to get, a feed which marks each tool needing service in their calendar when their servicing is due.

Generating the iCalendar data is simple. The following method from tool_controller creates an event for each tool and inserts it into a calendar. The to_ical call at the end of the method get the calendar as a string which can be served to the user. Note that this method assumes the @tools variable has already been set (you could always add a call to Tool.find(:all) at the start of the method if needed).

def generate_ical
  cal = Icalendar::Calendar.new
  @tools.each do |tool|
    # create the event for this tool
    event = Icalendar::Event.new
    event.start = tool.inspection_date
    event.end = tool.inspection_date
    event.summary = "Service of " + tool.name + " is due."
 
    # insert the event into the calendar
    cal.add event
  end
 
  # return the calendar as a string
  cal.to_ical
end

Next, we add the icalendar feed to respond_to in the tools_controller’s index method. We’ll make this call the generate_ical method to get the calendar data.

def index
  @tools = Tool.find(:all)
 
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @tools }
    format.ics  { render :text => self.generate_ical }
  end
end

And now you should be able to open your calendar application and subscribe to the feed straight from the tools controller using a URL like http://example.com/tools.ics

Easy filtering by optional criteria in Rails applications

Posted on December 11th, 2007 in Nerdy,ruby,ruby on rails by toholio

I’ve frequently needed a very simple search method that allows partial matches for any combination of fields in a table. The following snippet shows how an ActiveRecord derived object might have a filter to allow for selection of records given a set of partial values.

class YourClass < ActiveRecord::Base
   def self.filter( partial_values )
    # don't bother at all if there is no search object
    return find(:all) unless partial_values
 
    con_string = ""
    con_array = []
 
    # build collection of conditions
    partial_values.each do |key,value|
      if value != "" then
        con_string += " and " if con_array.size > 0
        con_string += "#{key} LIKE ?"
        con_array << "%#{value}%"
      end
    end
 
    # construct the actual conditions array
    conditions = [con_string]
    con_array.each { |item| conditions << item }
 
    find(:all, :conditions => conditions)
  end
end

To use this you would obtain a set of search parameters, one for each filterable column, and pass it to YourClass.filter as a hash to get the matching rows.

So if you had a table with title and category columns you might create a page containing a form to collect partial value for filtering. When creating the form, assuming you will use Rails’ form helpers, the fields_for :collection function is nice as it will allow for easy collection of a hash for the field values.

<% form_tag your_object_path, :method =>"get" do %>
	<% fields_for :partial_values do |f| %>
		Title contains: <%= f.text_field :title %><br />
		Category contains: <%= f.text_field :category %><br />
	<% end %>
	<%= submit_tag "Filter items", :name => nil %>
<% end %>

Then once the form is submitted you would get the appropriate results in your controller using:

@your_objects = YourClass.filter( params[:partial_values] )

MacOS X PIC toolbox

Posted on September 13th, 2006 in Electronics,Nerdy by toholio

I recently needed to install all the PIC programming tools I use on several Macs. Since people often ask for help installing these kinds of things I’ve decided to put together an installer package containg all the tools I use for the majority of my PIC’n needs. Hopefully someone else will find it useful.

The installer contains universal binaries for:

  • Jeff Post’s PK2 v2.01 – for operating the PICkit2 programmer hardware
  • GPUTILS v0.13.4 – assembler, linker, etc
  • sdcc v2.6.0 – C compiler

I have only tested the installer and resulting binaries on Macs running 10.4.7 (x86 and PPC) so if you try it under a different version of OS X, please let me know how it works.

The following installer contains all three packages (you can choose which ones to install).

Metapackage icon.
PIC toolbox (8.1MB)

IMPORTANT:The installer wont reconfigure your PATH, MANPATH or SDCC_HOME environment variables automatically. The things to add are:

  • /usr/local/bin to PATH
  • /usr/local/man to MANPATH
  • SDCC_HOME=/usr/local

For most people these can be configured by opening a terminal and running the following commands:

echo 'export PATH=/usr/local/bin:$PATH' >> ~/.bash_profile
echo 'export MANPATH=/usr/local/man:$MANPATH' >> ~/.bash_profile
echo 'export SDCC_HOME=/usr/local' >> ~/.bash_profile

PIC micro-controller programming on MacOS X.

Posted on July 4th, 2006 in Electronics,Nerdy by toholio

For a long time I’ve been frustrated by the lack of tools for programming micro-controllers (PICs specifically) using MacOS X. Most bit banging serial programmers wont work with a USB-to-Serial adapter, though I’m told some commercial ones do. There are some USB programmers available but until recently I wasn’t able to find one that was compatible with the 16F88 (PDF, datasheet) and had MacOS drivers available.

Enter the PICkit 2

After finally getting tired of SSHing into a Linux box in another room every-time I wanted to write to a PIC I started looking for a USB based programmer with support for the 16F88. I was pleasantly surprised to see that the firmware for Microchip’s PICkit2 had been updated to work with the 16F88 (as of version 1.20). The PICkit is a nicely made unit (about 10cm x 4cm x 1cm) that can be bought, with a low pin count demo board included, directly from Microchip for under AU$100.


PICkit 2

This still left me with the problem of Mac drivers but it didn’t take long to find Jeff Post’s PK2, an open source program for working with the PICkit2.

Using PK2 with MacOS X

Version 2.00 of PK2 works well well with MacOS. Older versions may work too but I haven’t done much testing with them. The program is easy to build and there is a native HID report which means that there is no need for MacOS users to muck about with libusb. Very nice indeed. When building make sure you use the osxhid Makefile target (unless you really want to use libusb). Once built and installed PK2 can be used to update the programmer’s firmware. Everything should be good to go and the programmer should be able to see the PIC it is connected to like so:

tobie@Tea-Chest ~ $ pk2 -device

PK2 version 2.00 - 2006/07/02
 pk2 -device
Communication established. PICkit2 firmware version is 1.21.0

Device ID 0x0760
PIC16F88 Rev 5 found
  Family:         Midrange
  Program size:   0x1000 (4096) words, width 0x3fff
  Eeprom size:    0x100 (256) bytes
  ID location:    0x0
  ID size:        0x4 (4) bytes
  Device ID       0x0760
  Write burst     4
  Program command O
  Program mode    n
  Program timing  n
  Data timing     d
  Erase mode      0
  CP mask         0x0834
  Bandgap mask    0x0000 0x0000
  Config mask     0x3fff 0x0003
  Save osccal     0
  Save bandgap    0
  Command table   63 00 02 03 04 05 06 08 18 17 1f 1f ff ff ff ff

Handy resources

The PICkit 2 comes with a CD-ROM which contains lots of examples and code for the supplied PIC16F690 including several lessons which should help someone not familiar with PIC programming to get a good grasp on the basics. For other PICs there are many forums and mailing lists on the internet including Microchip’s own. A quick Google search should point you in the right direction.

For updates and discussion of PK2 there is the pickit-devel Google group.

I want a version of Skype that doesn’t suck.

Posted on May 14th, 2006 in Nerdy,Ranty by toholio

To be fair to the MacOS team that works on Skype they’ve got a lot of things spot on. Skype for MacOS X is a Cocoa app and it feels good, it works well with other programs and on the whole it fits in. There are a couple of things about it which annoy the socks off me though and out of them there are two that really stick out in my mind.

One of the problems could probably be blamed on the Mac developers working for Skype but the other is probably beyond their control.

Whinge #1 – The splash screen

UPDATE: Turns out there is an option in Skype’s preferences for this but there is no way to set it using the GUI. You can set the option using the standard defaults tool by running “defaults write com.skype.skype SKShowSplash NO” or, if you are living dangerously, open ~/Library/Prefences/com.skype.skype.plist in the property list editor and change SKShowSplash there.

Splash screens are something you rarely see on a Mac and they’re specifically listed as being a bad idea by Apple’s user interface guidelines. Despite this Skype throws one over the top of whatever you might be working on and, to make matters worse, doesn’t provide a way to get rid of it again. Even if you focus on another window it will remain hidden until the splash screen finally goes away.

Skype's splash screen

It’s not as though the splash screen achieves anything, you already know the program is loading from the way its icon bounces gently in the Dock (just like any program that’s starting up).

The splash screen also makes the option to have Skype start when you log in useless since it throws up its always-on-top-let-me-just-hover-in-front-of-what-you’re-doing splash screen right when you most want to start working on something.

Sadly, it looks like we’re out of luck as far as disabling it goes, at least for the time being. Windows users can start Skype with the /nosplash option and it will remain politely silent until it has something useful to tell the user. I tried editing the splash screen’s NIB file to move it or at least make it smaller but it seems that Skype checks the integrity of its files before launching. Very annoying.

Whinge #2 – Video support

The Mac client still doesn’t support video calls despite the length of time it’s been available in the Windows client. I don’t think this is really something that the developers can be blamed for though. It seems likely that who ever is in charge of deciding what the developers work on just doesn’t see platforms other than Windows as being very important.

I can live without video support but it’d be nice to have it as an option and there are times when it would be very handy. If it were feasible I’d just use iChat for video calls but that’d more or less throw cross platform use out the window, and if iChat was a decent cross platform option I wouldn’t bother with Skype at all.

Finding the right mobile phone.

Posted on April 30th, 2006 in Drivel,Nerdy by toholio

My mobile phone took a trip to the ground a couple of weeks ago so I’ve been looking at potential replacements. There are a few things I really keen on my next phone having:

Seems fairly simple, given a well defined list of “must have” features, to find a suitable phone right? Well it turns out that searching for certain mobile phone features is more than a little difficult.

The search

Deciding where to start looking was easy enough. The desired features limit choices to the higher end Nokia phones. I headed over to Nokia’s Australian site to see what they had that fit the bill. The site has a handy flash based tool to help you filter the available models based on the features you want.

Nokia mobile phone search

The problem is that it doesn’t allow for choosing between different types of the same feature. For example, you can filter out models that don’t have a “Web Browser” but there is no way to choose between phones with modern browser with features like what you’d find on a desktop and page mangling browsers that only support WAP or some kind of HTML light. There is also no option of filtering based on things like support for third party applications, etc. Poking around the site a bit more turns up some slightly more useful pages such as the Business phone comparison but they still lack the details a nerd really wants.

What do you really want

Since Nokia’s site is so useless are far as detailed searching goes I went to the Series 60 browser website to see which phones are listed as supporting it. The list isn’t long, in fact at the time of writing it only lists 8 phones most of which don’t interest me as they have features that annoy me such as qwerty keyboards or bizarre form factors. The common element between these phones is that they use the 3rd edition of the Series 60 operating system. This narrows down what I’m looking for but the problem is the same as before: there is no site that offers searching for a phone based on the operating system, much less a specific edition.

So I’m left with going through the product pages individually to find out the details I need. Not difficult but annoying.

What about other brands

The Motorola SLVR L7 and RAZR v3i both looked promising at first but it seems that support for Motorola’s phones in iSync is very poor and if you want to use Bluetooth for syncing it is completely absent in some cases. This probably isn’t Motorola’s fault but it stops me from wanting any of their phones. The really odd thing about this poor support is that Apple chose Motorola as a partner for iTunes on mobiles.

What does this all mean?

None of this is a big deal but it reenforces something: geeks really are a niche market. The details I’m looking for aren’t hidden but they aren’t made easy to find either.

It also seems that people are still buying phones based upon “checkbox” style features, e.g. they want a phone with a “web browser” but they don’t really care what type. This doesn’t matter of course but it’s annoying if you do care and have no way of separating them. Then again lots of people are probably still choosing a phone by walking into a sore and taking whatever looks good and comes with a plan they want.

Au revoir, mes petits dreadlocks.

Posted on March 19th, 2006 in Drivel by toholio

These really need to be thrown out.

A bundle-O-Dreads

It was fun and horrendously ugly while it lasted but I can’t remember why keeping them in a bag sounded like a good idea. Perhaps it’s time to test the flammability of the wax that was rubbed into them.

My plan to stop myself losing hair by trapping it inside dreads is now officially a failure.

Subversion + Dreamhost

Posted on March 17th, 2006 in Nerdy by toholio

Subversion logo.

One of the few things that was missing from Dreamhost when I signed up has now been added: Subversion repository hosting!

The new subversion section in the Goodies area of the Dreamhost control panel asks for a project name, ID and domain/directory along with a list of user-names and passwords. There is also the option of limiting repository viewing to just the provided user-names and passwords.

I haven’t experimented much yet but it appears to work well. All I need now is the ability to use WebDAV with an entire domain (not just a subdirectory).

« Previous Page