Tuesday, December 16, 2008

Ruby on Rails News Site

I haven't been very active on this blog recently, but I've been keeping plenty active on other endeavors. One of which is the Ruby Rails Review which my friend, Brian Burridge, announced last week. As he mentioned in the announcement I created a very easy to use CMS tool which allows us to drag-and-drop the news stories all over the page for placement (or addition and removal), as well as a bookmarklet to simplify the process of adding new stories. I've very happy with how it turned out, unfortunately no one gets to see it but he and I.


Tuesday, September 09, 2008

Campfire activity notifier for Gnome, KDE, or console

The 37signals blog points out a simply Ruby script for KDE that will give you a visual notification when a new message is posted to a Campfire chat room. I have modified that script to work for Gnome as well as KDE, and additionally a text console. I also made a few other additions such as:

  • Allow you to specify a specific chat room(s) as a command line argument
  • Multiple chats rooms can be monitored concurrently using threading
  • Added the Campfire logo to the notifications
  • Added some initial status messages to display login status, room topic, and current people in the room
  • Display of the last 3 messages of the current day's transcript so you know what's going on without need to login
  • Filter out ads
Here is my version of the script:
#!/usr/bin/env ruby

# == Synopsis
#      Program to monitor a campfire chat room
#      Modified from code provided at: http://www.snailbyte.com/2007/09/13/campfire-activity-notifier-for-kde/
#
# == Usage
#      campfireMonitor [roomName] [roomName] ...
#
# == Author
#      Steven Pothoven and Snailbyte Ltd.

require 'rubygems'
require 'tinder'
require "cgi"

class App
  VERSION = '0.1.1'

  def initialize arguments, stdin
    # default settings
    campfireSubdomain = 'mySubdomain'
    campfireUsername = 'user@email.com'
    campfirePassword = 'password'
    roomNames = ['Room1', 'Room2']
    if arguments.length > 0
      roomNames = arguments
    end

    @ui = 'gnome'
    @campfireIconPath = '/path/to/campfire-logo.png'
    # define you favorite audio player and audio file here for audio notifications
    @soundCommand = 'mplayer /usr/share/sounds/pop.wav'
  

    @campfire = Tinder::Campfire.new campfireSubdomain
    if @campfire.login campfireUsername, campfirePassword
      alert nil, "CampfireMonitor", "Successfully logged in #{campfireUsername}"
      @rooms = roomNames.collect { |roomName| @campfire.find_room_by_name roomName }
      # remove any invalid rooms
      @rooms.delete(nil);
      @rooms.each do |room|
        notify room, "CampfireMonitor", "Entered room."
        notify room, "CampfireMonitor", "Topic is: #{room.topic}.".gsub("'","")
        notify room, "CampfireMonitor", "Current users are:  #{room.users}.".gsub("'","")
      end
    else
      alert nil, "CampfireMonitor", "Failed to log in #{campfireUsername}"
    end
  end

  # display notifcation message
  def notify room, user, msg
    if msg and msg.size > 0
      msg = CGI.unescapeHTML(msg);
      if @ui == 'kde'
        system "dcop knotify default notify eventname \'#{user}\' \'#{''+@campfire.uri.to_s+'/room/'+room.id+'/'+room.name+': ' unless room.nil?} #{msg}\' '' '' 16 2"
      elsif @ui == 'gnome'
        system "notify-send -i #{@campfireIconPath} '#{user}' '#{''+@campfire.uri.to_s+'/room/'+room.id+'/'+room.name+': ' unless room.nil?} #{msg}'"
      else
        puts "#{room.name+':' unless room.nil?}#{user} - #{msg}"
      end
    end
  end
  
  # notify with sound
  def alert room, user, msg
    notify room, user, msg
    if @soundCommand and @soundCommand.length > 0
      system @soundCommand
    end
  end

  def run
    # first get any missed messages for today
    threads = []
    @rooms.each do |room|
      thread = Thread.new do
        room.transcript(Date.today).last(3).each do |m|
          if !m.nil? and m[:message] and m[:message].size > 1
            notify room, m[:person], m[:message].gsub("'","")
          end
        end
      end
      threads << thread
    end
    threads.each { |thread| thread.join}

    # listen for more messages
    threads = []
    @rooms.each do |room|
      thread = Thread.new do
        notify room, "CampfireMonitor", "Waiting for messages..."
        room.listen do |m|
          if !m.nil? and m[:message].size > 1
            unless m[:person] == "Ad"
              alert room, m[:person], m[:message].gsub("'","")
            end
          end
        end
      end
      threads << thread
    end
    threads.each { |thread| thread.join}

  end
end

app = App.new(ARGV, STDIN)
app.run
I'm sure you can think of plenty more customizations such as command-line options for all the default settings, etc. But I wanted to keep it fairly simple. One last thing, here is the cropped version of the Campfire logo I use for my notifications (campfire-logo.png):

Tuesday, September 02, 2008

Google Chrome (Chromium) JavaScript speed

Today Google announced and released their own web browser named Chrome (aka Chromium). They even made a nice comic book to describe the advantages of it.

One of the key features they advertise is faster JavaScript execution due to the V8 JavaScript VM. So, I decided to test it using my JS-BogoMips test.

Here are the results of my tests (Windows Vista on Intel® Core™2 Quad Q6600):
Firefox 3:
JS-BogoMIPS (3x) = (0.436779 + 0.446775 + 0.450888) / 3 = 0.444814

Chrome:
JS-BogoMIPS (3x) = (2.758552 + 2.884791 + 2.881541) / 3 = 2.841628

which is a 6.4x speed increase!

Wednesday, July 16, 2008

Tuesday, May 06, 2008

Keystroke and Field Validation with JavaScript

Yesterday, I provided a simple tool to demonstrate the differences between keydown and keypress events. Today, I'm going to apply that knowledge toward making a lightweight form validation library. This library will prevent invalid characters from being entered in form input elements which is useful toward preventing malicious data from being entered (think XSS), as well as ensuring data integrity (data is in the valid format, all required fields present, etc.).

Sample Form:



Alpha
Alphanumeric*
Date
Decimal
Digit
Email
Hostname
IP address
Integer
Punctuation
Real number
Time
Whitespace
custom
type
format


* denotes required field.




The form above should only allow valid characters in each input field - this is your keystroke validation. Furthermore, for fields that require a specific format, when you leave a field with invalid formatted data it should provide an immediate visual indication of the error by setting a fieldWithErrors CSS class on invalid fields. Additionally, a fv:onInvalid event is fired on the invalid element to allow custom events handlers to provide additional actions. For example, enter a number in the date field and tab out. The field will be outlined in red from the fieldWithErrors CSS class and the message, "Date must be yyyy-mm-dd" will be shown by the handling of the fv:onInvalid event. Note: the CSS class will be removed automatically when the field is corrected, and a corresponding fv:onValid event will be fired to allow the custom code to clean up after itself.

Validation rules are defined as Regular Expressions. If you are not familiar with Regular Expressions here is a good reference. Additionally, many predefined regex rules for various validations can be found at the regex library.

Several common data types and formats are defined by default in the library, but it also provide the mechanism to add you own data types. In the custom entry, the type entry allows you to specify an on-the-fly keystroke validation regular expression, and the format entry allows you to specify an on-the-fly field format validation regular expression.

The Validate Form button demonstrates the action you would want to perform before a form submission. It invokes a validateAllFields function which just runs all the field validations (and invokes corresponding CSS rules and issues events). It also returns an array of the invalid field names in case you want to build a list of errors (like the Rails flash messages).


Usage Instructions

Sample Usage:

<script src="javascript/formValidation.js"></script>
<script>
var vf = new FormValidation();
vf.addValidationForField("date", "date", "date");
</script>

addValidationForField requires 3 parameters:

  1. The identifer of the field to add validation for

  2. The name of the data type to use for keystroke validation

  3. The name of the data format to use for field validation

In this sample all the names are the same, but they usually wouldn't be.

Just doing the above will prevent invalid characters from being entered in the data field and can indicate when the field is invalid.

When a field is changed, the format validation is run and will do two things.

  1. It will mark invalid fields are the fieldWithErrors CSS class. This can be used to appropriately highlight the error to the user. For example, the following CSS rule will outline the field in red:

    .fieldWithErrors {
    border: 3px solid red;
    }

  2. An event will also be issued in the field to indicate whether or not the field is valid. The events to watch for are fv:onInvalid and fv:onValid. These events can be used to hide/show error messages such the following which will display a pre-defined error message:

    $$('input').each(function(inputElem) {
    inputElem.observe("fv:onInvalid", function() {
    $(this.identify() + "-error").show();}.bind(inputElem));
    inputElem.observe("fv:onValid", function() {
    $(this.identify() + "-error").hide();}.bind(inputElem));
    });

    Or any number of other actions. For example, you may wish to display a popup error message such as those provided by Prototype Window or add messages to an error flash area as commonly done in Rails apps or toggle the submit button as enabled/disabled. Using these events allows you to add whatever actions you desire when the
    validation fails (or passes).



Download
formValidation.js