Working with Rails

Recommend Brian on Working With Rails


Powered

Building Tempo with Rails, Part VI

Posted by Brian Sam-Bodden Tue, 15 Jan 2008 05:00:00 GMT

Rails

In this installment we are going to build the Dashboard page of the Tempo application. The first incarnation of the Dashboard page will serve as the entry point/main page of the application and its main function will be to provide an interface for users to report time against a project-activity combination.

The user story that we are targeting is:

TMPO-29: “User enters Time” Business Critical [OPEN] 40 points 0% unassigned

The description above is from the Agile Project Management and Collaboration tool Caimito One. The “User enters Time” story is business critical, it is still OPEN, we have estimated 40 complexity points to it, is 0% completed and it has not been assigned to any team member (or no team member has volunteered for it!)

The description of the user story is "As a User I would like to enter time against a project and activity by providing a starting and ending time"

User Interface

Based on the story description I’ve come up with a rough sketch of what I picture the Dashboard page looking like after the first pass:

tempo dashboard sketch

The sketch above shows 3 different areas:

  • Date Selection: A Calendar-style component that will enable the user to select a given (active) date to enter time
  • Time Entry Details: A form that will provide drop-downs for the Project, Activity, Start Time, End Time for the TimeEntry as well as a text area for a description. Optionally the user will be allowed to enter time as a number of hours to be reported against the given date (with no specific start or end times(1)).
  • Daily Summary: A table displaying the time entries reported for the active date.

(1) Notice that I’ve just created a new requirement that was not present in the original User Story. In our work to fulfill the main User Story we will set the stage to satisfy this new requirement but we should really create a new issue (story) to tackle that new piece of functionality (of course first we should check with the project owner and/or stakeholders)

Dashboard Controller

I started by creating the skeleton code and tests for the Dashboard Controller:

/> script/generate rspec_controller dashboard   
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/dashboard
      exists  spec/controllers/
      exists  spec/helpers/
      create  spec/views/dashboard
      create  spec/controllers/dashboard_controller_spec.rb
      create  spec/helpers/dashboard_helper_spec.rb
      create  app/controllers/dashboard_controller.rb
      create  app/helpers/dashboard_helper.rb

Since we want the dashboard to be the default page for our application we can modify the config/routes.rb accordingly:

map.connect '', :controller => "dashboard", :action => "index"

With the skeleton in place I can now do a little planning about what I need to build.

A bit of Design

Here's what I know about the Dashboard page so far:

  1. The Dashboard page can only be shown if there is a user logged in. (done, taken care by the restful authentication plug-in)
  2. When the user first navigates to the Dashboard page, the current date should be shown in the calendar date picker and on the “blog” style display on the time entry form
  3. The Daily Work table should show all TimeEntries for the current user for the selected date
  4. When the user selects a new date form the calendar date picker the "current date" (the date which under the times entered will be reported) should change.

Create the Views

Let’s start by creating an index.rhtml template in the Views/dashboard directory. The index template will render three partials; one for a blog-style date, the TimeEntry form and one for the Daily Work table. The partials will be _current_date.rhtml, _form.rhtml and _time_entries.rhtml respectively.

views/dashboard/index.rhtml

The listing below shows the contents for index.rhtml. I used some of the CSS styles provided by ActiveScaffold to keep the look and feel consistent.

<div class="active-scaffold">
  <div class="create-view view">  
    <% form_tag :action => 'create' do %>
      <h4><div id="current_date_div"><%= render :partial => "current_date" %></div></h4>
      <ol class="form" >
        <%= render :partial => 'form' %>
        <p class="form-footer">
          <%= submit_tag "Create" %>
        </p>
      </ol>
    <% end %>
  </div>
</div>

<br />
<p>
<div id="time_entries_div">
  <%= render :partial => "time_entries" %>
</div>
</p>   

The index.rhtml view renders a form (which body is contained in the _form.rhtml partial), the current date which is render by the partial _current_date.rhtml. Finally at the bottom we have a section that contains the daily work table summary which is rendered by the _time_entries.rhtml partial. Let's take a look at each one of those partials next:

views/dashboard/_current_date.rhtml

The idea here is to render a blog style data block as shown below:

tempo dashboard sketch

To render the blog style date I have a CSS snippet that I use to style a partial containing the current date. The partial _current_date.rhtml is shown below:

<div class="dateblock">
  <div class="dateblock_month">
    <%= "#{Time::RFC2822_MONTH_NAME[@current_date.month-1]}" %>
  </div>
  <div class="dateblock_day">
    <%= "#{@current_date.day}" %>
  </div>
  <div class="dateblock_year">
    <%= "#{@current_date.year}" %>
  </div>
</div>

Notice that I use an instance variable current_date that will be set in the index method of the dashboard controller if it cannot be retrieved from the session:

  def index
    unless session[:current_date] 
      session[:current_date] = Time.today  
    end
    @current_date = session[:current_date]
  end

In the controller the method to render the partial and update the instance and the session variable follows:

  def current_date
    session[:current_date] = Time.parse(params[:current_date])
    @current_date = session[:current_date]
    render :partial => 'current_date'
  end

The CSS code for the dateblock is shown below (I've found it on a CSS site but I can't remember where):

/*-------------------------------------------------
DATE BLOCK
-------------------------------------------------*/
.dateblock {
  text-align: center;
  width: 50px;
  font-family: sans-serif;
  border: solid 1px black;
  padding-top: 5px;
  color: white;
  background-color:black;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.22em;
  font-family: sans-serif;
}

.dateblock_month {
  font-size: 12px;
}

.dateblock_day {
  font-size: 26px;
  position: relative;
  top: -2px; 
}

.dateblock_year {
  font-size: 12px;
  position: relative;
  top: -2px;
}

views/_time_entries.rhtml

For the Daily Work table showing all TimeEntries for the current user for the selected date we use the _time_entries.rhtml partial. This partial makes use of ActiveScaffold's ability to embed a scaffold in another controller, or view. To accomplish this we use the

render :activescaffold => 'timeentries'
which will call the render_component passing a specific set of conditions (to be appended to the SQL select statement) and a custom label for the scaffold table:


<%= render :active_scaffold => 'time_entries', 
           :conditions => 
             ["user_id = ? AND YEAR(start) = ? AND MONTH(start) = ? AND DAY(start) = ?",
              @current_user.id, @current_date.year, @current_date.month, @current_date.mday], 
           :label => 
             "Time Entries for #{Time::RFC2822_DAY_NAME[@current_date.wday]}, #{Time::RFC2822_MONTH_NAME[@current_date.month-1]} #{@current_date.day} #{@current_date.year}" %>

In the controller we need to modify the index method to also filter the collection of TimeEntry objects retrieved:

  def index
    unless session[:current_date] 
      session[:current_date] = Time.today  
    end
    @current_date = session[:current_date]
    @time_entries = TimeEntry.find(:all, :conditions => ["user_id = ? AND YEAR(start) = ? AND MONTH(start) = ? AND DAY(start) = ?", @current_user.id, @current_date.year, @current_date.month, @current_date.mday])
  end

We also need a time_entries method to render the TimeEntry(s) based on the current_date in the session:

  def time_entries
    session[:current_date] = Time.parse(params[:current_date])
    @current_date = session[:current_date]
    render :partial => 'time_entries'
  end

The daily work table should now display all the TimeEntry(s) for the current/selected date:

tempo dashboard sketch

views/_form.rhtml

The form partial is fairly simple and provides elements to select the project, the activity, time picker for the start and end dates, an optional total hours worked field and a text area to enter comments associated with the work being reported.

The complete source for the partial is shown below:

<%= error_messages_for 'time_entry' %>

<!--[form:time_entry]-->
<li class="form-element">
  <dl>
    <dt><label for="time_entry_project">Project</label></dt>
    <dd><%= collection_select 'time_entry', 'project', current_user.projects, 'id', 'name' %></dd>
    <%= observe_field 'time_entry_project', :update => 'time_entry_activity', :with => "project_id", :url => { :controller => "dashboard", :action => "load_activities" } %>
  </dl>
</li>

<li class="form-element">
  <dl>
    <dt><label for="time_entry_projects_activity">Activity</label></dt>
    <dd><%= select 'time_entry', 'projects_activity', ['--select a project--'] %></dd>
  </dl>
</li>

<li class="form-element">
  <dl>
    <dt><label for="time_entry_start">Start</label></dt>
    <dd><%= time_picker Time.now, {:time_format => '12', :minute_step => 30, :prefix => 'time_entry', :field_name => 'start', :time_separator => ':'} %></dd>
  </dl>
</li>

<li class="form-element">
  <dl>
    <dt><label for="time_entry_end">End</label></dt>
    <dd><%= time_picker Time.now, {:time_format => '12', :minute_step => 30, :prefix => 'time_entry', :field_name => 'end', :time_separator => ':'} %></dd>
  </dl>
</li>

<li class="form-element">
  <dl>
    <dt><label for="time_entry_hours">Hours</label></dt>
    <dd><%= text_field 'time_entry', 'hours'  %></dd>
  </dl>
</li>

<li class="form-element">
  <dl>
    <dt><label for="time_entry_comment">Long Description</label></dt>
    <dd><%= text_area 'time_entry', 'comment', 'rows' => 12, 'cols' => 45 %></dd>
  </dl>
</li>
<!--[eoform:time_entry]-->

A little Ajax

Let's dissect the form contents. First at the very top we have a form element that displays a drop-down for the projects that the current user is part of. Since we have specific activities per project we need to use some Ajax magic to populate the project activities drop-down.

<li class="form-element">
  <dl>
    <dt><label for="time_entry_project">Project</label></dt>
    <dd><%= collection_select 'time_entry', 'project', current_user.projects, 'id', 'name' %></dd>
    <%= observe_field 'time_entry_project', :update => 'time_entry_activity', :with => "project_id", :url => { :controller => "dashboard", :action => "load_activities" } %>
  </dl>
</li>

<li class="form-element">
  <dl>
    <dt><label for="time_entry_projects_activity">Activity</label></dt>
    <dd><%= select 'time_entry', 'projects_activity', ['--select a project--'] %></dd>
  </dl>
</li>

To accomplish this I use the observe_field tag, Rails lets you listen to events on a field such as the value of a field to which you can respond by making an Ajax call to an action handler with the current value of the field being observed sent to the action handler in the post data of the call. In the case above we are updating the drop-down time_entry by invoking the action load_activities in the controller, which is shown below:

  def load_activities
    project = Project.find(params[:project_id])
    @projects_activities = project.projects_activity
  end

Time Picking

To enable time picking on the form fields for start and end times I used Thong Kuah TimePicker plug-in which can be found at http://rubyforge.org/projects/timepicker/. As described in the read me file, this plug-in follow the usage of ActionView::Helpers::DateHelper closely.

Below is a preview of what the time picking drop-downs will look like:

tempo dashboard sketch

To install the plug-in I again use Piston:

/> piston import svn://rubyforge.org/var/svn/timepicker/trunk vendor/plugins/timepicker
Exported r4 from 'svn://rubyforge.org/var/svn/timepicker/trunk vendor/plugins/timepicker' to 'vendor/plugins/timepicker'

With the plug-in installed you can now use time_picker(datetime, options = {}) in your views.

In our case the usage is shown below:

<li class="form-element">
  <dl>
    <dt><label for="time_entry_start">Start</label></dt>
    <dd><%= time_picker Time.now, {:time_format => '12', :minute_step => 30, :prefix => 'time_entry', :field_name => 'start', :time_separator => ':'} %></dd>
  </dl>
</li>

<li class="form-element">
  <dl>
    <dt><label for="time_entry_end">End</label></dt>
    <dd><%= time_picker Time.now, {:time_format => '12', :minute_step => 30, :prefix => 'time_entry', :field_name => 'end', :time_separator => ':'} %></dd>
  </dl>
</li>

Calendar Picker

For the current date selection I'm using a set of plug-ins that work well with ActiveScaffold. Calendar Date Select can be found at http://code.google.com/p/calendardateselect/. There is also a bridge to integrate it into ActiveScaffold at http://wiki.activescaffold.com/wiki/published/CalendarDateSelectBridge:

/> piston import http://calendardateselect.googlecode.com/svn/tags/calendar_date_select vendor/plugins/calendar_date_select
Exported r154 from 'http://calendardateselect.googlecode.com/svn/tags/calendar_date_select' to 'vendor/plugins/calendar_date_select'
/> piston import http://activescaffold.googlecode.com/svn/bridges/active_scaffold_calendar_date_select_bridge vendor/plugins/active_scaffold_calendar_date_select_bridge
Exported r634 from 'http://activescaffold.googlecode.com/svn/bridges/active_scaffold_calendar_date_select_bridge' to 'vendor/plugins/active_scaffold_calendar_date_select_bridge'
/> 

Once installed, I placed the code for the date picker in the main application layout (application.rhtml). The snippet below shows only when the controller is the dashboard controller and the action is the index action:

<!-- ============ --> 
<!-- Right Column -->
<!-- ============ --> 
<div class="Right">
  <div class="col">
    <% if current_page?({'controller' => 'dashboard', 'action' => 'index'}) -%>
      <h1>Select a Date</h1>
      <%= calendar_date_select_tag 
          :current_date, 
          @current_date, 
          {:embedded => "true",
           :onchange => "new Ajax.Updater('current_date_div', '/dashboard/current_date?current_date=' + $H({current_date: this.value}).toQueryString(), 
                        {asynchronous:true, evalScripts:true}); 
                        new Ajax.Updater('time_entries_div', '/dashboard/time_entries?current_date=' + $H({current_date: this.value}).toQueryString(),
                        {asynchronous:true, evalScripts:true})"} 
      %>
    <% else -%>
      <h1>[[Help Title]]</h1>
      <p>[[Help Body]]</p>
    <% end -%>
  </div>
</div> 

Finally we need a create method in the controller to handle the creation of the new time entry when we submit the form:

  def create
    project = Project.find(params[:time_entry][:project])
    projects_activity = ProjectsActivity.find(params[:time_entry][:projects_activity])
    @time_entry = TimeEntry.new
    @time_entry.user = current_user
    @time_entry.project = project
    @time_entry.projects_activity = projects_activity
    start_time = Time.parse(params[:time_entry][:start])
    end_time = Time.parse(params[:time_entry][:end])
    @time_entry.hours = params[:time_entry][:hours]

    unless session[:current_date] 
      session[:current_date] = Time.today
    end
    @current_date = session[:current_date]
    @time_entry.start = Time.utc(@current_date.year, @current_date.month, @current_date.mday, start_time.hour, start_time.min)
    @time_entry.end = Time.utc(@current_date.year, @current_date.month, @current_date.mday, end_time.hour, end_time.min)

    if @time_entry.save
      flash[:notice] = 'TimeEntry was successfully created.'
      redirect_to :action => 'index'
    else
      render :action => 'index'
    end
  end

In the code above we first find the project and the project activity based on the parameters posted with the form, next we create a new TimeEntry object and set the values on the form. The start and end times on the time entry are calculated using the current_date value and the hour and minutes selected on the time pickers.

tempo dashboard

In the next installment we will move beyond the simple capabilities implemented so far and begin thinking about what it takes to polish a product so that it can be ready for mass consumption. Until the next time.

Posted in ,  | 2 comments | no trackbacks

Categories

Archives

Syndicate