Tuesday, February 21, 2012

Schedule appointments with Rails 3 and jQuery

Problem:  I needed a dynamic appointment scheduler that will instantly run a date chosen by a user against all the available time slots for that date.  The scheduler then needs to dynamically hide the time slots that have already been chosen.

Solution:  jQuery's datepicker plugin and .ajax() function.

I'll demonstrate this in an MVC context.  All code can be had on Github.


First, we need to create an appointment model.  So in the terminal run:

We use a string datatype for 'date' because we'll want to present the calendar date format ('yy-mm-dd') immediately to the user.  Setting 'hour:string' allows the records to have leading zeros which allows us to set four digits for any hour e.g. 1300 and 0900, which in turn makes string pattern matching easier.  We'll use military time to help facilitate this as well.

Now, for our appointment class:

Here, we ensure that no model is persisted unless its date and hour properties are set.  We also declare a qualifier for the hour's uniqueness key - forcing any duplicate hours under the same date to be rejected.  This server-side filter is critical for cases when two users both clear the client-side javascript validations at the same time.  If both attempt to submit the same hour and date combo, Active Record will prevent the more recent submission from persisting.

In the view, we load the necessary jQuery-UI CSS file at the top, followed by calendar, hour_picker, and appointment_form divs.  These divs will switch their hidden/shown status throughout the scheduling workflow.  Javascript files required by jQuery along with our custom appointment.js file round out our view template.  Here is the entire view template for reference.

The controller contains our three needed RESTful routes.  If you are confused about REST and how it relates to Rails, read this first followed by this.  Our controller:

Here, our 'new' route allows us to use 'new_appointment_path' in our views.  The 'index' action allows us to match chosen dates to available hours.  The 'create' action persists the data and I added some error handling as well.

For our routes, we need only add the following:

resources :appointments

Here, no appointment-specific routes need to be hardcoded - an advantage of RESTful architecture.


Upon visiting '/appointments/new', a user sees nothing but the jQuery calendar because we've hidden the 'hour_picker' and 'appointment_form' divs using jQuery's .hide() function which is triggered upon page load.  document.ready function calls the .datepicker() function rendering the calendar.  Clicking a datebox in the calendar itself triggers the 'onSelect:' callback function.

The 'onSelect:' function reverses the user interface by hiding the calendar and showing the hour_picker div.  'dateText' is the date value chosen by our user - we pass this value to our 'findHours' function which does nothing for now because no dates have ever been chosen.  We'll revisit this when we try to save the same date twice.

The uncloaked hour_picker div offers the user a list of standard business-day hours.

Here, each table row is a button which triggers the 'nextPage' function (seen below) with two parameters - the button's ID and a string that is a duplicate of the button's class.  Matching the button's class to a 'nextPage' parameter will allow us to block, hide, or disable more buttons in the future in order to prevent duplication.

Here, we continue our liberal use of jQuery's .hide() and .show() methods.  We also set input values to the user-chosen date and the user-chosen hour respectively.

Finally, the user is shown submission form.  The values have been added to hidden fields to prevent the user from changing them at this point in the process.  Instead, to allow the user to review their selections before submission, we use jQuery's .append() to peg the chosen date and hour to specific divs.


So now a different user wants to book that exact same date and time.  They hit a calendar date, say February 21, 2012, and, along with moving the user to the next phase, the onclick listener triggers the 'findHours()' function which is no longer useless:

This function dynamically checks the user-chosen date for any of its hours that may have already been booked.  We pass the chosen_date to jQuery's very useful.ajax() function which creates a GET request by attaching the chosen_date value to the URI string.  We set the 'cache' property to false causing a current timestamp to automatically be attached to the URI - we don't use the timestamp here, but it may be useful later.  Also, we don't want to cache the data should the user revisit the scheduler in the same session.

.ajax() is a higher-order function, meaning that if certain conditions are met, it returns a 'success' callback.  This callback takes the hours of our user-chosen-date, returned as a comma-delimited sting to the index view (more on this later) - and converts the hours into the elements of a new array through string manipulation.

By sending a GET request to /../appointments, we call the index method in our appointments_controller.  This method...

...takes the GET request's matched_date value and queries the database with it.  We then reduce the date to a collection of hours and make the result viewable with the instance variable @new_dates.  Finally, since we'll be passing this html back to our new.html.erb view, we need to disable the Rails layout lest we send a huge string of unnecessary html wrapping the html that we want.

Speaking of new.html.erb, you'll notice this snippet..

<div id = "hidden_hour_div"></div>

..is where we'll peg the string returned from our index method.  The second part of the findHours() function changes this string into an array.  We then cycle through the array, attaching a '.' in front of each element so that jQuery can recognize each element as a particular class in our view and hide those classes accordingly.  Why do we add the '.' after the fact?  Because ID and class tokens must begin with a hexadecimal ([0-9A-Za-z]) so we can't call our <tr> classes '.0900' for instance.

An alternate strategy for findHours() is to have the data converted to JSON in the controller and then parsed with jQuery.parseJSON() in appointment.js.  But this would require increased steps in both the Rails initialization directory, and in your Appointment's model.

So we've covered the scheduler's main components as well as the workflow for creating a new date/hour record and the process of preventing the duplication of a date/hour record.

I packaged this code as a Ruby Gem, which provides a scaffold for you to build a more robust scheduling feature.

Friday, February 3, 2012

Ship generators with your Ruby gems

Say I'm building a gem and I want it to do three things.  

  1. create a new route in the gem user's routes.rb file 
  2. add some code that will be executed every time they start their app, and  
  3. place a controller in their rails controller directory.

How would I allow the gem user to do this with one command?

Let's build a quick gem for a rails 3.0+ app. This post assumes that you understand the basics of creating a Ruby gem.

In the terminal run:

Here, when Rails sees the 'generators' directory, the generator we are going to create becomes available to the 'rails generate' command. The 'templates' directory will store all the files and text the user may want to add to their app. Now open install_generator.rb and add the following:

For the three methods above to work, you need to specify 'thor' as a dependency in your my_gem.gemspec file. There, you will also need to specify your 'lib' directory as an executable (for an example of a gemspec file go here).

These three methods will be executed when your user runs the generator.
I use the 'template' method instead of the better-sounding 'copy_file' method so that we can place all of our files into a 'templates' directory. The 'template' function adds this directory to the generator's path. The ‘template’ method also executes any ERB tags found in your template files, and, while this can be powerful, we need to escape them if we're placing 'html.erb' files into the user's 'view' directory lest Rails throws a nomethod error when trying to execute them - we do this by using a double percent (%%) like so:

So far, in the templates directory, we've made the files we want to copy into our gem user's rails app.  In the install directory, we've made the actual generator itself.  And in the root of our gem, we've ensured that our gemspec file lists 'thor' as a dependency and the 'lib' directory as an executable.

We're ready to create the gem.

Thursday, October 27, 2011

Publish Adobe Captivate results with Ruby on Rails

Adobe allows you to use the results derived from Captivate quizzes without requiring each of your students to have a separate Adobe ID.  

There are several tutorials showing how to publish these results using PHP - and your Adobe installation comes with the necessary PHP scripts for making this happen - but if you prefer Rails, then you were out of luck, so let's see what I did or install the Ruby gem.

First, Captivate needs to know that we want to report quiz results. In your Captivate quiz project, hit edit > Preferences > Reporting (located 4th from the bottom of the left-hand menu), then at the top check ‘Enable reporting for this project’.  After checking this, check ‘Internal Server’ and then hit ‘configure’.  In the popup window that comes up, you’ll see 4 mandatory fields.  The first field is the most important as this is where you'll link Captivate to the familiar Rails routes - type http://www.example.com/internalreport.  PHP projects will have a ‘.php’ appended to the end of that URL but since we're creating a Rails route, there is no need to append an ‘.rb’ to the end of this.

Second, in your Captivate installation you’ll find the PHP script with the right logic at ‘<yourCaptivateInstallation>\Adobe Captivate 5.5\Templates\’.  Open this and it should look like:

Now we need to translate the PHP to Ruby for our Rails controller.  Create a Rails controller such as ‘captivate_controller.rb’ so that we have a place where ‘http://www.example.com/InternalServerReporting’ will be routed to.  Don’t forget to add:

(or whatever you named your controller and data-processing method) to config/routes.rb.  Now for the Ruby translation of the PHP file:

As you can see, POSTing to InternalServerReporting creates a params hash and then creates a directory for Captivate results with the values of these parameter keys. Now, go to your Rails root and change the permissions for your 'doc' directory to ‘read, write, and execute, - make sure the change is recursive so that it affects all the directories within the ‘doc’ directory.  

Everything is finished so let’s test.  Go through a quiz on your site as if you were a student and on the last slide you’ll see a ‘Post Result’ button that was automatically added when you checked ‘Enable Reporting For This Project’.  Use whatever username and email combo you want and then exit the quiz and look in your ‘doc’ folder of your Rails root and you should see a "Results" directory followed by the three directories that you named (after you specified your site’s URL) followed by an XML file with the results of the quiz you just took. Or you can spec this out.

In future posts, I’ll discuss how to send an email with these results to the student who took the quiz. I’ll also post about ensuring that the username and email submitted by your students matches the username and email that they used to sign up for your site.  And how to get those captivate SWF files working in Rails.

Check out my Ruby gem for this