5 things for productivity when working from home

Posted by chris olsen on August 26, 2007

Not to long ago I worked in my little cubicle just like many of you, but after a while I realized that I wanted to work on my own since I knew that is what I would enjoy the most. Most days at the office were the same, I would come in, grab a cup of coffee then get to work. I was able to clock many solid hours in a day. When I left my job to work on my own I was confident that my work ethics would make the transition a breeze…wow was I wrong. My productivity went down the toilet, mainly due to the fact that I no longer a boss to report to at the end of the day.

So here are 5 things that I found were crucial to getting things done in a day working from home:

Learn one thing at a time

I am the kind of person that always has new things that I want to learn, and with all this extra time I figured I could learn it all, and how wrong I was. I was learning little and spending a lot of time doing it. I was seeing no results as time passed and that was frustrating. Now that I revamped my approach to learning new things, I see dramatic results in a short time. This is not just great for my skill levels, but motivates me throughout the day.

Eliminate distractions

Distractions are all around us and we are so used to them that we don’t immediately see them for what they are, but think of them as necessities. I am referring to email, IM, phone, etc. At my office job all three of the mentioned items were a part of my work day. I had to keep email opened otherwise I could miss something important. IM was there to either ask someone work related questions or whether or not they wanted to go grab a coffee. The phone was right there to make sure that if anyone had a question for me I could answer it right away.

When working from home it didn’t take long to realize that these distractions were wasting a lot of time. I have read that it usually takes about 10-15 minutes for a person to get in the working mode and fully focus on a task, and if interrupted, can take another 10-15 minutes to get back in the game. With these costly transition times it became obvious that the distractions had to be better managed. Even though they are being labeled as distractions they are still required. I do have to keep in contact with clients and friends, but I find it best to schedule a couple of 15 minute blocks in the day where that is all I do, making it my new activity that has my focus. It is amazing at how much extra time in a day that you can get from this alone.

Say adios to multitasking

I remember job interviews where I was asked if I was a multitasker. Knowing they wanted to hear that I was, I would tell them exactly that. In truth I am anything but a multitasker and the same is true for most other people in the world. Sure I can do many things at once, but I will, 9 times out of 10, be more efficient if I am able to concentrate on one thing at a time.

A person has to take advantage of this and one good way of doing it is to work in time segments. Set a start time and for one hour and devote all your attention to it. You will get a lot done in this hour and when complete it is one more notch on your productivity post for the day.

Take advantage of downtime

I always have certain times in the day where I know I will get a lot done, and certain times where the opposite is true. Instead of packing myself full of caffeine to turn the downtimes into uptimes, I found it was best to perform the tasks that don’t require a lot of mental energy. Personally, I take my dog for a walk or run around 3:00 in the afternoon. This way I don’t lose any up-time, but am still able to get something important done.

Don’t set overly high goals for the day

Instead of putting 10 things on your daily to-do list and only getting 3 things done, doesn’t it make more sense to only put 3 things on the to-do list and getting them all done? Not only will this give you the feeling of a productive day, seeing as you are 3 for 3, but it will also require you to screen the items that are to be marked as to-do and eliminate time spend on lower priority tasks.

When writing this article I used everyone of the mentioned points, and the result, something that I hope will add extra time to your day, and at the very least, remind me what to do if I start wasting time again.

RubyOnRails: Forms 102

Posted by chris olsen on August 24, 2007

As I mentioned in a previous article (Forms 101), I had some difficulties coming to RubyOnRails from an asp.net background seeing as certain things that were non-existent in asp.net were rather important in Rails. I am referring to the the controls contained within the html form tags. There was only one set in asp.net that a person had to become familiar with to be able to make things happen. In Rails there is a few sets of methods that render out the desired controls and each set has a purpose.

If you are not familiar with the various form blocks that exist within the Rails framework I suggest you give the Forms 101 article a read first and then come back to this one. This topic is not a complex one, but when I was learning I could never find a single source of information that listed all the form control methods, so that is where this comes in handy.

There are common names used throughout all the various method types that you may or may not already be aware of. Below are a list of the common method names.

  • text_field
  • text_area
  • select
  • checkbox
  • radio_button

There are, to my knowledge, three types of methods that exist that are based on the above names.

The first one is to append the _tag suffix to the method name, ex. text_field_tag, checkbox_tag. Each of these methods requires one argument, the parameter’s name. In the example it should be noted that the id and name of the control match the parameter name.

<%= text_field_tag :first_name %>
 
#will render to the web browser as
<input type="text" id="first_name" name="first_name"></input>

The big difference with this method is that on the server side the form values are accessed directly from the params[] array, ie params[:first_name], params[:last_name]. Having the form values stored like this makes it easy to quickly access the values and pass them to a method call, ex. a login authentication method (Member.valid(params[:user_name], params[:password]))

The second type consists of names that match the method names that were listed above, ex text_field, checkbox, radio_button. This method requires two arguments, where the first is the model name and the second is the parameter name.

<%= text_field :member, :first_name %>
 
#will render to the web browser as
<input type="text" id="member_first_name" name="member[first_name]"></input>

The key things to note are the values of the id and name attributes of the input tag where the model name is now included in each. So what does this do? The name parameter allows the request object to hold all the form parameters in its own sub-array that can later be accessed through the params array, ex. params[:member][:first_name]. The benefit to this is that it makes it easy to fill a model with all the form values as shown below.

def create
	@member = Member.new(params[:member])
end

The last method type is more geared to be used within the form_for block. They are much like the previous type mentioned except they are called through the block’s parameter and only require one parameter name although the html output will be the same. The reason for this is the form_for’s block parameter that the text_field method is called from. This block parameter will create the corresponding form control that matches whatever value follows the form_for, ex. in this case :member.

<% form_for :member, :url => member_url() do |form| %>
form.text_field :first_name
<% end %>
 
#will render to the web browser as
<input type="text" id="member_first_name" name="member[first_name]"></input>

The main benefit of this type is that it prevents you from having to define the model that the form control is for for each form control, and less is better.

Now that you have a good idea of what each type is for, it is time for the key point. You can, for the most part, mix the the types of form methods that reside within the form tags. Although the form.text_field etc must only exist within a form_for, all the others can exist whenever and wherever. This then allows you to easily obtain data through the form that does not match the model without too much effort.

Just to top things off, below is a bunch of common form methods that a person should be familiar with, although I am sure there is a few that I am missing. Hopefully this may clear up thing for some, and serve as a reminder for others.

<% form_tag do  %>
 
	Text Field Tag:
	<%= text_field_tag :task, :title %>
 
	Text Field
	<%= text_field :task, :title, :size => 30  %>
	<br>
 
	Text Area:
	<%= text_area :task, :title, :rows => 5, :columns => 30 %>
	<br>
 
	Select with simple array:
	<%=
	options = [1,2,3,4,5,6,7,8,9]
	select :task, :points, options
	%>
	<br>
 
	Select with hash table:
	<%=
	options = {:one => "First", :two => "Second", :three => "Last"}
	select :task, :points, options
	%>
	<br>
 
	Select control bound to list of models:
	<%=
	#create some tasks
	if Task.count == 0
	["Learn RubyOnRails", "Create practice site", "Create real world site"].each do |title|
	Task.create(:title => title, :points => 10)
	end
	end
 
	tasks = Task.find :all
	#select control must be bound to list of 1x2 array or hash
	select :task, :points, tasks.map{ |t| [t.title, t.points] }, :prompt => "Select..."
	%>
	<br>
 
	Another select bound to a model:
	<%= collection_select(:task, :points, tasks, :id, :title) %>
	<br>
 
	Checkboxes:
	<%= check_box :task, :complete, {:style => "color: red; font-size: 20px;"}, "yes", "no" %> Is Complete (yes no)
	<%= check_box :task, :complete, {:style => "color: red; font-size: 20px;"} %> Is Complete (1 0)
	<br>
 
	Radio buttons:
	<%= radio_button :task, :complete, "complete" %> Complete
	<%= radio_button :task, :complete, "incomplete" %> InComplete
	<br>
 
	Date Select Helpers:
	<!-- http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#M000577 -->
	defaults to the current date:
	<%= date_select(:task, :completed_on) %>
	<br>
 
	Setting the min and max value within in the list:
	<%= date_select(:task, :completed_on, :start_year => 1970, :end_year => 2000) %>
	<br>
 
	Hidden Field(seriously there is on here):
	<%= hidden_field :task, :title %>
	<br>
 
	Password:
	<%= password_field :task, :title %>
	<br>
 
	Password Check:
	<%= password_field :task, :title_confirmation %>
	<br>
 
	File:
	<%= file_field :member, :picture %>
	<br>
 
	<%= submit_tag "Submit this form" %>
 
<% end %>

Floating Forms

Posted by chris olsen on August 23, 2007

Web applications have come a long way in the last couple years to the point where they are now beginning to replace some of the desktop applications that we all have come to love. Even though I am a web developer I never liked the way the applications were too jumpy, by that I mean that to perform simple tasks you had to select an item from a list that would direct you to a new page containing a form. After submitting the form you were then redirected back the list of items that you originally made the selection from. Not only was the application jumping from page to page to perform the task, but when directed back the initial page it required a complete update. This update would not be that bad, if you are working with a simple CRUD application, but if the page contains a lot of dynamic data from other tables the update could be somewhat costly if your site has high traffic.

When I used to develop primarily with asp.net, I created a web control that, through the use of some simple javascript and css, allowed for a div tag to float above the rest of the form and contain the form to perform the create/update operation. Unfortunately, asp.net seemed to lack the ability to, through the use of ajax, obtain the required form for the database table I wished to create/update. The only way that I was able to make things happen was to have a number of controls on the page, each containing the form for the various tables I wished to modify. Things got messy very quickly.

RubyOnRails makes this fairly simple to do even for a person without a lot javascript experience, and that my friends, is what what this article is all about. This article does assume some RubyOnRails experience. Although I will be going over the whole process I will not spend a lot of time explaining details that are unrelated to the creation of the floating windows.

First thing that we have to do is create our project.

Projects 510 $ rails FloatingWindow
  create
  create  app/controllers
  create  app/helpers
  create  app/models
  create  app/views/layouts
  create  config/environments
  create  components
  ...
  create  doc/README_FOR_APP
  create  log/server.log
  create  log/production.log
  create  log/development.log
  create  log/test.log

To keep things nice and simple we create a simple Task model with just enough fields to get the point across.

Projects 511 $ cd FloatingWindow/
FloatingWindow 512 $ script/generate scaffold_resource Task
  exists  app/models/
  exists  app/controllers/
  exists  app/helpers/
  create  app/views/tasks
  exists  test/functional/
  exists  test/unit/
  create  app/views/tasks/index.rhtml
  create  app/views/tasks/show.rhtml
  create  app/views/tasks/new.rhtml
  create  app/views/tasks/edit.rhtml
  create  app/views/layouts/tasks.rhtml
  create  public/stylesheets/scaffold.css
  create  app/models/task.rb
  create  app/controllers/tasks_controller.rb
  create  test/functional/tasks_controller_test.rb
  create  app/helpers/tasks_helper.rb
  create  test/unit/task_test.rb
  create  test/fixtures/tasks.yml
  create  db/migrate
  create  db/migrate/001_create_tasks.rb
  route  map.resources :tasks
FloatingWindow 513 $

Now add the following code to the db/migrate/001_create_tasks.rb file

class CreateTasks < ActiveRecord::Migration
  def self.up
    create_table :tasks do |t|
      t.column :name, :string
      t.column :created_at, :timestamp
      t.column :completed_at, :datetime
      t.column :points, :integer
    end
  end
 
  def self.down
    drop_table :tasks
  end
end

Before we perform the migration we have to make sure that our databases are properly set up in the config/databases.rb file. Since watching the PeepCode screencast on Test First Development I have become a fan of using sqlite3 databases. If you have sqlite3 installed and wish to use them the following configuration settings should get you going. The test database is not required for this article since I will not be creating any tests (I can’t believe I just said that), but it speeds the testing process up which is why sqlite3 is a nice alternative to mysql until production.

development:
  adapter: sqlite3
  database: db/FloatingWindow_development

test:
  adapter: sqlite3
  database: ":memory:"
  verbosty: silent

If you are using mysql then you can use the default database settings, but you just have to make sure that you create the database through mysqladmin before continuing.

FloatingWindow 515 $ rake db:migrate
(in /Users/chrisolsen/Projects/FloatingWindow)
== CreateTasks: migrating =====================================================
-- create_table(:tasks)
   -> 0.0041s
== CreateTasks: migrated (0.0043s) ============================================

Since the generate scaffold_resource command does not create a form for the model that is the first thing that we will do. So create a _form.rhtml file in the app/views/tasks directory and insert the following.

<p>
	<label for="name">Name:</label>
	<%= f.text_field :name %>
</p>
 
<p>
	<label for="points">Points:</label>
	<%= f.select :points, 1..10 %>
</p>

To allow our forms to work nicely we have to use forms that will make the put/post requests through ajax. So to do this we will have to create two new controls, one for the update and one of the create, each of which uses the _form partial we created earlier.

#_floating_edit.rhtml
<% remote_form_for(:task, :url => task_path(@task), :html => { :method => :put }) do |f| %>
	<%= render :partial => "form", :locals => {:f => f} %>
  <p>
    <%= submit_tag "Update" %>
  </p>
	<a href="#" onclick="hideWindow()">Close</a>
<% end %>
 
#_floating_new.rhtml
<% remote_form_for(:task, :url => tasks_path) do |f| %>
	<%= render :partial => "form", :locals => {:f => f} %>
  <p>
    <%= submit_tag "Create" %>
  </p>
	<a href="#" onclick="hideWindow()">Close</a>
<% end %>

You may be wondering about the hideWindow() javascript call, and that is right around the corner, but first let’s create an application.rhtml template file. This file, at least for this example, will be where the div tags that perform the floating will exist as well as all the javascript and css. I shouldn’t have to say, but if you are using this for a live site you would want to create separate files for each of the later two.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
	<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
	  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
	  <title>Tasks: <%= controller.action_name %></title>
	  <%= stylesheet_link_tag 'scaffold' %>
		<%= javascript_include_tag :defaults %>
	</head>
	<body>
		<div id="floating_bg"></div>
		<div id="floating_window"></div>
 
		<p style="color: green"><%= flash[:notice] %></p>
 
		<%= yield  %>
 
	</body>
 
	<style type="text/css" media="screen">
		/* Base */
		body {margin:0; padding:0;}
 
		/* Visibilty */
		#floating_bg {display: none;}
		#floating_window {display: none;}
 
		/* Positioning */
		#floating_bg {position:absolute; top:0; width:100%; height:100%; text-align:center;}
		#floating_window {position:absolute; margin: auto; text-align:left; margin-top: 150px;}
 
		/* Style */
		#floating_bg {background-color: black;}
		#floating_window {background-color: white; padding: 10px; border: 4px solid #333;}
	</style>
 
	<script type="text/javascript">
 
		//functions
		function showWindow(width) {
			centerWindow(width)
			setVisibility("floating_bg", "block", .5);
			show("floating_window");
		}
 
		function hideWindow() {
			hide("floating_window");
			hide("floating_bg");
		}
 
		//helpers
		function setVisibility(id, displayType, opacity) {
			e = $(id);
			e.style.display = displayType;
			e.style["-moz-opacity"] = opacity;
			e.style["opacity"] = opacity;
		}
 
		function hide(id) {
			setVisibility(id, "none", 0);
		}
 
		function show(id) {
			setVisibility(id, "block", 1);	
		}
 
		function centerWindow(width){
			//set the proper left value
			var e = $("floating_window");
			e.style.left = ((window.outerWidth - width - 10) / 2) + "px";  //10 for the padding of 20
			e.style.width = width + "px";
		}
 
		//page events
		$("close_window").onclick = function() {
			hideWindow();
		}
 
	</script>
	</html>

The javascript methods that are shown above are pretty basic and the only ones that you have to be concerned with are the hideWindow() and showWindow(). The hideWindow() method, which was seen earlier, is the method attached to the onclick event of the close link within the form. The showWindow() is the method that will be called within rjs file.

The other important thing to notice are the div tags at the top of the screen. It is there that the form partials created earlier will the inserted into.

<div id="floating_bg"></div>
<div id="floating_window"></div>

To access these floating forms we will have to add a couple of links that contain the ajax calls to the list of tasks.

#tasks/index.rhtml
...
<%= link_to_remote "+ Create", :url => new_task_path(), :method => :get %>
<table>
<% for task in @tasks %>
  <tr>
    <td><%= link_to 'Show', task_path(task) %></td>
    <td><%= link_to_remote "Edit", :url => edit_task_path(task), :method => :get %></td>
    <td><%= link_to 'Destroy', task_path(task), :confirm => 'Are you sure?', :method => :delete %></td>
		<td><%= task.name %></td>
		<td><%= task.points %></td>
  </tr>
<% end %>
</table>

Next we have to create the rjs files that will manage the insertion of the create/update forms into the floating div tags. The first line will perform the insertion of the partial and the second line calls the javascript function in the application.rhtml file that will show the window on the page.

#edit.rjs
page["floating_window"].replace_html :partial => "floating_edit", :object => @task
page.call("showWindow", 300)
 
#new.rjs
page["floating_window"].replace_html :partial => "floating_new", :object => @task
page.call("showWindow", 300)

Before everything works we have to make some minor updates to the tasks_controller in the respond_to block by adding “format.js”. This will allow the controller method to respond the rjs request. This must be inserted into the new and edit methods.

respond_to do |format|
  format.html
  format.js
end

The last thing that has to be done, is to update the page after the remote_form submits the post/put request. This can be done in a couple ways. The first, which totally goes against the main reason that I wanted to create the floating forms, is to cause the page to refresh itself. This page refresh will cause the floating window to revert back to its original floating state where the display was set to “none”, but requires that the page hits the database for all the data that was untouched by form submission. The code to perform this is shown below.

#create.rjs and update.rjs
page.redirect_to tasks_url()

To hide the floating form and update/insert the form data into the page you have to insert the following code into the rjs files instead. To do this you would first have to create another partial class that holds the tr and td tags containing the CRUD links and the task details and update the index.rhtml file to use the new partial. This partial now makes it easy to insert the new row or overwrite the updated row in the task table (I will allow you to create this partial and insert the unique row ids).

#create.rjs	
page["the_table_id_of_the_task_list"].insert_html :before, :partial => "list_line", :object => @task
 
#create.rjs	
page["the_table_row_#{@task.id}"].replace_html :partial => "list_line", :object => @task

Using this definately allows your application to have that little extra zing that may make a huge difference in the end. However, it can be seen that there is quite a bit of extra work to make it all happen so I, personally, would not want to do it if it was not required, but then again that is just me. As mentioned earlier this could make a huge difference on a page with a lot of dynamic data unrelated to the data requiring a refresh and that is where I can see this method being useful. Another thing to watch out for is the abuse of the javascript. There are still some people on browsers that don’t have javascript enabled as well as many people on mobile devices that may suffer if you don’t have a non-javascript backup plan.

Floating Window

RubyOnRails: Forms 101

Posted by chris olsen on August 20, 2007

Coming from an asp.net background creating forms was pretty simple, mainly because whenever a new .aspx page was created the form tag was automatically added to the new page, so a person really didn’t ever have to create a form tag.

In RubyOnRails you have a few more options. To demonstrate this I have create 5 examples, each of which renders a form that can be used to create a new task. The differences are highlighted in red to make things a little more visible.

<h3>#Example 1</h3>
<%= start_form_tag :controller => :tasks, : action => :create %>
	<%= text_field_tag :title, params[:title] %>
<%= end_form_tag %>
 
<h3>#Example 2</h3>
<% form_tag :controller => :tasks, : action => :create do %>
	<%= text_field_tag :title, params[:title] %>
<% end %>
 
<h3>#Example 3</h3>
<% form_tag :controller => :tasks, : action => :create do %>
	<%= >text_field :task, :title %>
<% end %>
 
<h3>#Example 4</h3>
<% form_for :task, :url => {:controller => :tasks, : action => :create} do |t| %>
	<%= t.text_field :title %>
<% end %>

The first example is now deprecated so it is pretty safe to avoid that one, so there is not much use in going over it any further.

The only difference with Example 2 is the removal of the deprecated end_form_tag and containing the form within a block as can be seen by noticing the do on the end of the first line. If you look at the rendered html output it can be seen the names and ids of the form elements match that of the param name that was used, in this case :title.

<form action="/tasks/create" method="post">
	<input id="title" name="title" type="text" />
</form>

Using form controls with the _tag postfix are useful when the data contained within a form does not correspond to a model. One example of this would be a login form containing a username and password. Another example could be a form that emails the admin comments by users.

Not having the data match a model also means that the form data that is submitted to the server is accessed through the params array using a key matching the name of the form element

def create
	title = params[:title]
	...
end

In example number 3 the text_field method is used instead of the text_field_tag. If you compare the parameters that are passed to each of the methods, the first parameter to the text_field method is the name of the model. If you then examine the rendered html the id and the name are prefixed by the model name.

<form action="/tasks/create" method="post">
	<input id="task_title" name="task[title]" size="30" type="text" />
</form>

When accessing the form values on the server side, instead of having to access them individually, they are now contained within a sub-array accessed by the key which is the value of the first parameter passed to the text_field method.

The benefit of creating a form like example 3 is that it allows for the form to contain data belonging to more than one model. So lets say your program wants to be able to keep track of a person’s address history so you will be keeping this information in a separate table to the person’s personal info. You could then obtain the person’s name, password, etc as well as their current address within one form.

<% form_tag :controller => :tasks, :action => :create do %>
	First Name:
	<%= text_field :user, :first_name %>
	Last Name:
	<%= text_field :user, :last_name %>
 
	Address 1:
	<%= text_field :address, :address_1 %>
	...
<% end %>
 
#controller code
def create
	user = User.new(params[:user])
	user.addresses << Address.new(params[:address])
	user.save!
end

The last example uses the form_for method to generate the form tags. The first parameter passed to the method is a reference to model that was created on the server within, if you are using REST, either the new or edit methods. The main difference with the form_for method are the methods that are called within the form block, which is discussed in another article.

This was a topic of confusion when I first started reading up on Rails, so hopefully this will clear things up for others that are new to the framework.