Funny Software Video Sunday

Posted by willy on August 24, 2008

Well, I thought I would start a new section on this site called funny software video sunday. Where I’ll post funny software video’s every Sunday. This video is of Steve Ballmar selling windows 1.0

Hacking will_paginate to use your own javascript function

Posted by willy on August 23, 2008

Since Rails 2.0 came out the default pagination for records has been removed, you are now on your own to handle record pagination. One of the more popular options is to install a plugin called will_paginate. This plugin for Rails is much like the old Rails one but with some more advantages. Some of these are it’s ease of use, being able to use it in a Model and there is less code to get it to work.

Installing will_paginate is pretty easy. You navigate to your rails root project directory and run the script/plugin command like so:

script/plugin install svn://errtheblog.com/svn/plugins/will_paginate

This may not work with windows if you don’t have svn setup. You may need to download it from another location and install it. Once you have the plugin installed you should be able to test it by opening up your controller and replacing one of the queries in it with a find_by_paginate() call. The example below does a basic query with the extra parameters.


  def show
	@messages = Note.paginate_by_user_id(session[:user], {:page => params[:page], :per_page => 20, :order => 'notes.updated_at DESC'})
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @note }
    end
  end

The above snippet has some extra parameters which are pretty obvious to what they do. The next step is to alter your view page to enable the pagination.

<% @messages.each do |message| %>
	<%= h message.text %>
<% end %>
<%= will_paginate(@messages) %>

This will get the page number links to display in your view. If everything works you should see it, and be able to loop through multiple pages without a problem. Now the hacking part comes in. The goal is to change the pagination links to call a custom JavaScript function. This will come in handy if you want to load up ajax, or have some need to do validation on a page before the user goes to the next page. I won’t go into these different solutions here thought. I’ll leave that to you.

Since you have will_paginate installed lets make some modifications to it. The helper function is what controls the link display. Open up the /vendor/plugins/will_paginate/lib/will_paginate.rb file.
we are going to change the if statement in the page_link_or_span function to look like something below.

    def page_link_or_span(page, span_class = 'current', text = nil)
      text ||= page.to_s
      if page and page != current_page
        if @options[:remote]
          @template.link_to_remote text, {:url => params.rec_merge!(:page => page)}
        elsif @options[:function]
          @template.link_to_function text, "javascriptfunction('#{@options[:argument]}',#{page})"
        else
          @template.link_to text, url_options(page), :rel => rel_value(page)
        end
      else
        @template.content_tag :span, text, :class => span_class
      end
    end

There are two new options in this function. One which is remote, and the other function. You don’t need remote, but if you find it useful go ahead and add it. In the function elsif statment you’ll notice a call to javascriptfunction. This should be dynamic but for this post’s sake it’s done like this so it’s easier to understand. This javascriptfunction is the actual function name that will get called. The options :argument is a variable argument we pass to the custom function. Once you’ve changed this, restart your dev server. This will allow the plugin to be reloaded with your modifications.

Now the next step is to add the the new arguments to your will_paginate call.

<%= will_paginate(@messages, {:function => true, :arguments => params[:action]}) %>

Notice that we added a :function => true and a :arguments. For this sake we are just passing in the action of that was called. You should change this to whatever you want.

Then the next step is to code your javascript function to be called. In one of your JavaScript files create a new function called javascriptfunction. This should just be a basic for now. Replace it with your own.

function javascriptfunction(arg) {
	alert(arg);
}

Once this is done you should be able to reload the page, and now when you click on a link to paginate to the next record, it will call your javascriptfunction. If you get a alert message with the action name that was called in your controller it means it worked.

Now you can do all sorts of stuff with pagination, including adding ajax to paginate results, doing some crazy validation, or just annoying your users :P

Enjoy - Take a load off fanny

Posted by willy on August 16, 2008

First Harvest 2008 - Sweet Corn, Beans and Lettuce. Yeah!

Posted by willy on August 10, 2008

Today was the first harvest from the garden. The corn, green beans, and lettuce were ready for the picking. The watermelon, cantaloupe and pumpkin still have a ways to go but are looking good. Here are some pics of the garden and of some of the pickings.

Wordpress Code Formatting

Posted by willy on August 10, 2008

Wordpress code formatting is horrible, it takes such a long time to get the characters to work right so it actually displays code correctly. The last post of mine had me pulling my hair out but after doing a quick search I found a Java application which handles all the code formatting for you. You just copy in your code, click the button and then paste the new code into your wordpress blog. It’s simple and easy.

Here’s the link to the site, and the tool. Thanks Scott! you rock!

Creating a character counter textarea in Rails 2

Posted by willy on August 10, 2008

This is a simple, cool little effect I’ve recently decided to implement. The purpose is simple, it’s to allow users to see how many characters are left when they enter a text in a textarea. I implemented this effect on the users editable settings page for a user bio field where they can enter up to 140 characters to describe themselves. I used Rails 2.0 to make a simple helper so I can reuse the code and so I can have a textarea with a counter anywhere on the site.

The only javascript library you’ll need:
jQuery - The Write Less, Do More, Javascript Library

Make sure to download the library and extract it to your public/javascripts folder. This will let you call it in your viers/layouts/application.html.erb layout or which ever layout header you’re using. The javascript I’ve used used the jQuery function name so it shouldn’t conflict with prototype or any other library you have.

I’ve added this in between the elements in my /layouts/application.html.erb.

<script src="/javascripts/jquery-1.2.6.min.js" type="text/javascript"></script>
<script>jQuery.noConflict();</script>

Once that is added you’ll need to add 2 javascript functions which you’ll need to put in a new .js file or an existing .js file that you already have. I have a application.js to contain functions which I may use frequently.

function updateStatusTextCharCounter(value, e, limit, button) {
	len = value.length;
    jQuery('#status-field-char-counter').html('' + (limit-len));
	if (len > limit) {
		if (jQuery("#" + button).attr('disabled') != 'disabled') {
			jQuery("#" + button).attr('disabled', 'disabled')
			jQuery("#" + button).addClass('update-button-disabled')
		}
	} else {
		if (jQuery("#" + button).attr('disabled') == true) {
			jQuery("#" + button).removeAttr('disabled');
			jQuery("#" + button).removeClass('update-button-disabled')
		}

		if (len > (limit - 10)) {
			jQuery('#status-field-char-counter').css('color', '#d40d12' );
		} else if (len > (limit - 20)) {
			jQuery('#status-field-char-counter').css('color', '#5c0002' );
		} else {
			jQuery('#status-field-char-counter').css('color', '#cccccc' );
		}
	}
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

The first function is used to call an update to change the status text on how many characters are left. The 2nd function handles the load events to calculate characters based when the page is loaded. That should be all the javascript needed now.

The next part is creating the helper function which will be able to reuse though out the application so anytime we need a character count textarea field we just have to call one function. This is the fun part! :P

I’ve placed my helper in the application_helper.rb file, so it can be easily reused. The code is pretty self explanitory, so I don’t think I really need to walk through it. The comments explain which option does what.

  def textarea_counter_field(options)
    #options has a couple options
    #1.:id = which is the id of the text field, if you put a id with a underscore
    #        the name of the textarea will be wrapped in textareas to make it
    #        easy when processing the form. for example user_profiletext becomes
    #        user[profiletext].
    #2.:button = is the id of the submit button. There is javascript that will not
    #            enable the form to be submitted if the max chars has been reached or
    #            is more.
    #3.:rows = rows of the textarea
    #4.:cols = cols of the textarea
    #5.:text = the text that should appear in the textarea.
    #6.:limit = the number of allowed characters.

    name = ""
    if !options[:id].index('_').nil?
      name = options[:id].sub('_', '[')
      name << "]"
    end

    result = "<script type=\"text/javascript\">
              addLoadEvent(function() {
                $(\'#{options[:id]}\').focus();
                updateStatusTextCharCounter($(\'#{options[:id]}\').value,null,#{options[:limit]},'#{options[:button]}');
              });
              </script>\n"
    result << "<span id=\"chars_left_notice\" class=\"numeric\">"
    result << "<strong id=\"status-field-char-counter\">#{options[:limit]}</strong> characters left"
    result << "</span>"
    result << "<br>"
    result << "<textarea id='#{options[:id]}' name='#{name}' rows='#{options[:rows]}' cols='#{options[:cols]}' "
    result << " onblur=\"return updateStatusTextCharCounter(this.value, event, #{options[:limit]},'#{options[:button]}');\""
    result << " onkeyup=\"return updateStatusTextCharCounter(this.value, event, #{options[:limit]},'#{options[:button]}');\""
    result << " onfocus=\"return updateStatusTextCharCounter(this.value, event, #{options[:limit]},'#{options[:button]}');\">"
    result << "#{options[:text]}"
    result << "</textarea>"

    return result
  end

The next part is going to your view, where you want your text area to be placed. Mine is in my profile page.

<%= textarea_counter_field(:id => 'user_profile', :button => 'update-submit', :rows => 6, :cols => 60, :text => @user.profile, :limit => 140) %>

That should be it. Let me know if you find it useful, or want to work on it with me just shoot me a email or leave a comment. I’m pretty new in Rails, so please don’t rip on my to hard :) All in all I hope it makes your life easier.

New Theme

Posted by willy on August 02, 2008

I upgraded the theme. I thought that it was about time as the old layout was kind of cool but someone actually ripped it off, stole all my wordpress files and put their name on it and give it to lots and lots of people. So instead of going through all the hard work of creating a new theme for someone else to steal I decided just to change it to a theme that someone else had made and give them credit for it. Take that you evil wordpress template stealers!

I found this theme by sheer luck when crusing the web and landed on some guys rails site. With a link to his blog and his published theme. So here’s the link if you want to use it for your blog. http://quotedprintable.com/pages/scribbish

A rant on usability 1

Posted by willy on August 02, 2008

My CIO  gave a little speech on simplicity in our company meeting awhile ago. He made a lot of sense and simplicity is something I’ve learned as a web developer to be very useful. Most developers don’t want simple because there is so many cool things we can do.

Anytime you design a page you should consider this:

1) What is an absolute necessity to have on the page.
2) How easily identified is each field to the user and do they know what your using it for?
3) Which is the most convenient and obvious place to put content.
4) How is the form or page going to load.

I’ll give examples of each starting with the registration form I posted in the previous post. So you may have a visual of what I’m talking about.

1) What is an absolute necessity to have on the page

When designing the registration form the only fields I need first from a user.
- first name
- last name
- username
- password
- email

That’s it and to be honest you don’t need first name or last name, but I put these fields so if a user puts in a user name that already exists a list of user names can be generated based on a combination of these values and availability.

What I didn’t do:
- avatar upload
- personal bio
- current mood
- country
- state
- zip
_ gender
- any extra content (user search??, login form)

These don’t make sense, you don’t need them right now for the user to create an account. Fields or content that aren’t a necessity for a process to work correctly should not be used.

2) How easily identified is each field to the user and do they know what your using it for?
Each field needs to have a corresponding and specific label to what that field actually does and what it’s going to be used for on your site. Honesty will go a long way. If you can tell your users what your using it for (if it’s not totally obvious) they are going to be more likely to put information in it.

You may notice that on the right side of the input text field is a green box. This green box tells the user what the field is going to be used for and the label tells the user this is for your Email. These green boxes aren’t necessary to have on every field and frankly would get very annoying. But obviously it does play an important role on fields which the user will be concerned with.

3) Convenient Content
In order for user experience to be fast, easy and quickly understandable you must place your elements on the page in a easy way. You have to remember that users want the fastest easiest way to do what they want to do on your site. They don’t want to fill in a million fields, click through wizard pages and have to move the mouse across the screen to click something.

Lets take an example of posting a new topic in a message board. Most message boards are loaded with a huge amount of features like a full javascript editor, a smiley face popup. Now taking the perspective of the user, the user’s only goal now is to get his message posted. Do you think the user is concerned with all these features? HELL NO! All they want is to post a topic title, and a message and wait for a response. So get rid of the crazy crap on the page that probably only 1% of your users will actually use. If they really want a feature they’ll go back anyways and update it.

Once the crazy crap is gone, what? no don’t get rid of it. Make it intuitive, choose options for the user. If a user puts a smiley face in the message, just switch it to a damn little smiley graphic. Why would a user care? in fact wouldn’t you think that if the application saw a smiley face in txt format they would be like cooOol it automatically created a smiley graphic for me? I know I do. (There are times it’s not useful like posting code) :P

So make sure all your crazy crap is intuitive in the application. Concentrate on how fast you can complete the application. You should be able to use the keyboard to navigate to each field. If you can’t and have to pick up the mouse, your going to be pissing people off!!! The mouse is a horrible instrument, it’s slow, clicky and can even be used to blind people (optical).  Layout your content in a single order, top to bottom. The order is the only way you can control your flow on how you want the user to use your application.

The next thing that you need to make sure is that if you have a dependency that something has to be done before or after in order for them to complete your application, don’t make them go back and start over. If you notice this in your application try and think of a way to combine the two. People don’t want to go back especially if you have multiple steps in your interface. Simply adding a + add button into the interface which creates your dependencies will be very pleasing to you users as they won’t have to restart everything and fill in the same fields again and again.

This isn’t the end of this crazy rant on usability issues but I have one last thing to add and that is how your page is going to load. Everyone knows that a slow page is bad. There are lots of things you can do to speed up your page but as a usability issue don’t make 500 fields, with 20 drop downs that have million options in them on a single interface. Drop downs, or anything pre-loaded with content like Tree views are death to page load. I’m not suggesting to not use them but don’t let the user or yourself have a million plus options to select from. Remember KISS and the next time your at your favorite application like twitter, gmail, or flickr take a look and try and notice some of these things I’ve said in those applications. You’ll see why they are popular and are used quite frequently.

That’s all for now. I’ll make sure to post more annoying usability features as I encounter them. Sorry for writing a damn book. It’s not even user friendly but now you can feel my pain :P

Ruby on Rails 2.0 Customizing Model Validation Error Messages.

Posted by willy on June 30, 2008

Tonight I was working on a new registration form for a site I’m developing called Whoaty. I decided that I would slowly and very meticulously get every detail the way I want it. Since I’m new to rails this also gets me time to learn and counter the learning curve.

My registration form looks something like this right now:

registration form

This is the basic plain old registration form with a little css.  Now when you hit the submit button to start processing the form my Model comes back and displays which fields are not valid.

Registration Form with Errors

The first thing we can do to dress this up is change the header and message. The header is the “8 errors prohibited this user from being saved”. The message portion is  “There were problems with the following fields:” which contains information on which fields my model puked on. At my registration form I have the following code which we should change to something like this.

<%= error_messages_for :user %>

change to

<%= error_messages_for :user,
 :header_message => "Oops Please Try Again!",
 :message => "We had some problems with some of fields." %>


The change was adding :header_message and :message.

Next we can apply some css. Rails wraps up all our error messages in a couple of css classes. You can specify your own class in the error_message attribute also but for my instance it will work just as the default. The first class is called .errorExplanation and I’m going to style it now with the following code in CSS

.errorExplanation {
     background-color:#FFEAE8;
     border:1px solid #FF8B7F;
     color:#000;
     text-align:left;
     vertical-align:top;
     padding-top:5px;
     padding-left:20px;
     padding-bottom:10px;
     margin-top:3px;
     margin-bottom:10px;
}

.errorExplanation h2 {
     color:#F0775E;
}

.errorExplanation ul {
     list-style-type: disc;
     list-style-image: url(../images/icons/exclamation.png);
     list-style-position: inside;
     margin:15px
     padding:3px;
}

Now what we have is a sort of good looking error message box as shown below. The next step will to use scriptaculous to shake the error message. This is kind of cool.

Now to get the error message to shake we need to know when we have errors. The simplest way I was able to do it was to add the error_messages attribute to the form like below and then check if it was != nil. If it wasn’t nil then we have error messages and we can shake it!

<% form_for :user, :url => users_path do |f| %>
    <% if f.error_messages != nil %>
        <%= error_messages_for :user,
        :header_message => "Oops Please Try Again!",
        :message => "We had some problems with some of fields." %>
        
    <% end %>
   <% #form stuff goes here %>
<% # end form %>

If the shake doesn’t work make sure you have the javascript library included in your header. Rails provides easy access just by doing

<%= javascript_include_tag :defaults %>


or

<%= javascript_include_tag :effects %>

Once you got the shake down we can do one more cool feature with CSS and that is changing the border to red on fields that were invalid. When Rails returns an error message it also wraps the individual field with a error message and have a class attribute called “fieldWithErrors”.

To change the border now on any text field that has an error I used this code below. This changed the inputs for text fields and password fields.

.fieldWithErrors input[type="text"],
.fieldWithErrors input[type="password"] {
	border-color:#FF8B7F;
}

The last portion to changing the message is specifing a better return message in the actual Model. The default Model looks something like this:

validates_presence_of :username
validates_format_of :username,
	:with => /^[A-Z0-9_]*$/i,
	:message => "must contain only letters, " +
                "numbers, and underscores" 

validates_presence_of :email
validates_format_of :email,
	:with => /^[A-Z0-9._%-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i,
	:message => "must be a valid email address"

with_options :if => :password_required? do |pass|
	pass.validates_presence_of :password,
	                           :password_confirmation
	pass.validates_length_of :password, :within => 4..40
	pass.validates_confirmation_of :password
end

validates_uniqueness_of :username, :case_sensitive => false
validates_uniqueness_of :email, :case_sensitive => false

validates_length_of :username, :within => 3..64
validates_length_of :email, :within => 5..128

Each different type of model validation has different attributes in which mostly you can change. Here is the document api link which has lots more examples. The point is you can change and hack these to say whatever you want.

So the end result looks a little something like this:

That’s about all I learned so far about doing custom error messages in rails 2.0. If anyone has anything else they found let me know. Please remember I’m not an expert. I’m just posting what I’ve found out.

Cleanup and Upgrade

Posted by willy on June 28, 2008

Well I decided to do a reboot of the blog, and do a fresh install and help hopefully secure the site from spammers, and other hackers and since the version I was using had security holes in it, it  it seemed like a good time to do it. Plus the new version has a lot of new features. I want to do a redesign also and integrate some of these new features that came with the upgrade.