Web Accessibility For Developers

Posted by Brian in Accessibility (October 6th, 2010)

Recently, I polled people via Hacker News and Twitter about the things they’d like me to share about web accessibility given my experience as both a web developer and a daily user of assistive technology. The questions I received are great, and I’ll be writing a series of posts over the next few months about various ways developers can improve the accessibility of their sites for not only disabled users, but for everyone.

To kick this off, you can read my latest article in the October issue of PragPub Magazine, entitled “HTML5: Accessibility For All” where I discuss some of the new accessibility features in HTML5 that make sites easier to use for both screen readers and mobile devices.

In the coming weeks, you can expect to see articles on

  • Improving audio and video for the web
  • Colorblindness
  • Learning disabilities
  • more concrete progressive enhancement
  • Motor impairment issues
  • low vision issues

and many more.

I hope you follow along.

Connecting to SQL Server from a Mac (Again)

Posted by Brian in Rails, tips (September 20th, 2010)

Connecting to SQL Server is one task I have to do regularly when I work on Rails applications for clients that use Microsoft technologies. I usually set my machine up and don’t really worry too much about how it all comes together.

Recently I had to do the installation completely from scratch. I followed Ken Collins’ comprehensive walkthrough, but I ran into a problem – I wanted to use RVM. Ken’s tutorial uses MacPorts to install the Ruby ODBC bindings, and I wasn’t using Ruby via MacPorts.

Everything out there wasn’t working for me even when I followed Ken’s article on RVM.

Here’s what ended up working for me.

First, I used MacPorts. Then I installed the ports I needed:

sudo port install unixodbc
sudo port install freetds +odbc

I modified /opt/local/etc/freetds/freetds.conf to look like this:

[my_dev_server]
  host = 192.168.1.58
  port = 1433
  tds version = 8.0

Then I modified /opt/local/odbcinst.ini to point to my FreeTDS configuration:

[FreeTDS]
Decscription = FreeTDS driver for SQLServer
Driver = /opt/local/lib/libtdsodbc.so
Setup = /opt/local/lib/libtdsodbc.so
FileUsage = 1

Finally I modified /opt/local/odbc.ini and created my ODBC DSN.

[my_dev_server_dsn]
Driver=FreeTDS
Description=My Server Connection
Servername=my_dev_server
Server=my_dev_server
Port=1433
Database=killer_app

Note that the servername matches the servername defined in the FreeTDS configuration file.

Then I went and installed the gems I needed for my project

gem install ruby-odbc
gem install dbi  -v=0.4.1
gem install dbd-odbc -v=0.2.4
gem install activerecord-sqlserver-adapter -v=2.3.9

But when I ran my Rails application, attempts to connect to models failed.

ODBC::Error: IM002 (0) [iODBC][Driver Manager]Data source name not found and no default driver specified. Driver could not be loaded

It’s using iODBC which comes with OSX. It wasn’t using UnixODBC at all!

To fix that, I had to reinstall the ruby-odbc gem and instruct it to use the unixodbc path. This is what ultimately fixed things for me:

gem install ruby-odbc -- --with-odbc-dir=/opt/local

After that, everything worked again!

Accessible Rails Applications – Let Cucumber help you test for Accessibility

Posted by Brian in Accessibility, Rails (August 27th, 2010)

Developers working with Rails are constantly looking for ways to use Cucumber to test their JavaScript. One thing I’ve come to love about Cucumber’s default setup is that it does not work with JavaScript at all, which actually helps me ensure that my applications work for uses without JavaScript enabled.

if I write a Cucumber story that tests to see if a delete works, and I’ve used the default “link_to” method for deletes made popular by the Rails scaffolding, my cucumber feature will fail. I’ll be shown the Show page instead of the “successfully deleted” message.

Keep that in mind as you work through your applications – See what stories break when you don’t have JavaScript enabled and reconsider your implementations.

Reordering Records with acts_as_list and Metaprogramming

Posted by Brian in Howto, Metaprogramming, Rails (May 28th, 2010)

Using acts_as_list, you can reorder items by adding a “position” column to your database and then easily sort records.

  class Project < ActiveRecord::Base
     acts_as_list
  end
  
  class Task < ActiveRecord::Base
     acts_as_list
  end
  

The acts_as_list plugin also provides you methods to manipulate the position.

  • @project.move_to_top
  • @project.move_to_bottom
  • @project.move_higher
  • @project.move_lower

In a current project, I have multiple items that need reordering, which means I'd be duplicating a lot of controller actions and other code across my controllers and views. I'll show you how I used metaprogramming to significantly reduce that duplication.

The Route To Reordering

First, we need some routes. Add this to your routes.rb file:

  %w{projects tasks}.each do |controller|
    %w{move_higher move_lower move_to_top move_to_bottom}.each do |action|
      instance_eval <<-EOF
        map.#{action}_#{controller.singularize} "#{controller}/:id/#{action}", {:controller => "#{controller}", :action => "#{action}"}
      EOF
    end
  end

We use an array of controllers, then we have another array of the four actions, and we just make the named routes. This generates

    move_higher_project        /projects/:id/move_higher                            {:action=>"move_higher", :controller=>"projects"}
      move_lower_project       /projects/:id/move_lower                             {:action=>"move_lower", :controller=>"projects"}
     move_to_top_project       /projects/:id/move_to_top                            {:action=>"move_to_top", :controller=>"projects"}
  move_to_bottom_project       /projects/:id/move_to_bottom                         {:action=>"move_to_bottom", :controller=>"projects"}

        move_higher_task       /tasks/:id/move_higher                            {:action=>"move_higher", :controller=>"tasks"}
         move_lower_task       /tasks/:id/move_lower                             {:action=>"move_lower", :controller=>"tasks"}
        move_to_top_task       /tasks/:id/move_to_top                            {:action=>"move_to_top", :controller=>"tasks"}
     move_to_bottom_task       /tasks/:id/move_to_bottom                         {:action=>"move_to_bottom", :controller=>"tasks"}

Metaprogramming really cuts down on work when you use it correctly. This turns out to be a pretty nice way of generating route patterns that share common attributes.

Keep The Control Centralized

Now let's step it up a notch. Each controller is going to need the four reordering methods. The logic will be identical except for the object they work on and the URL they redirect to when they're finished.

Let's create a module that adds controller methods to match these routes. We'll add it into our controllers where we need it.

Create the file lib/reorder_controller_actions.rb:

  module ReorderControllerMethods

      %w{move_higher move_lower move_to_top move_to_bottom}.each do |action|
        define_method action do
          klass = self.class.name.split("::").last.gsub("Controller", "").downcase.singularize.camelize.constantize
          item = klass.find(params[:id])
          item.send(action)
          flash[:notice] = "The #{klass.to_s} was reordered."
          redirect_to :action => "index"
        end
      end
  end

That module defines four controller actions and calls the corresponding method on the model, then does a redirect back to the index action. It'll be the same everywhere I use it, so I also gain consistency with metaprogramming.

We need to add this to the bottom of config/environment.rb so that our controllers can make use of it.

  require 'reorder_controller_methods'

Then, in each controller where we need this module, we mix it in with include

class ProjectsController < ApplicationController
  include ReorderControllerMethods
end

class TasksController < ApplicationController
  include ReorderControllerMethods
end

Stop and REST for a second

Is it appropriate for me to do it this way? I'm going to argue that while technically the position of something could be sent to the update action, I want specific redirection and notification to occur when I change the order of elements. The logic was getting too nasty in the update action, so I split each thing apart, so I went with this approach instead.

An Improved View

Next, we need some buttons for our index pages with arrows on them so the user can trigger the ordering. How about a simple helper that can generate all four buttons for us?

  def reorder_buttons(object)
    thing = object.class.name.camelize.downcase
    result = ""
    [
      {:action => "move_higher", :label => "↑"},
      {:action => "move_lower", :label => "↓"},
      {:action => "move_to_top", :label => "↑↑"},
      {:action => "move_to_bottom", :label => "↓↓"}
    ].each do |item|    
      result << button_to("#{item[:label]}", send("#{item[:action]}_#{thing}_path", object) )
    end
    result
  end

We use an array hold the buttons. We use hashes within the array to map the action to the label of the button. We then iterate and generate buttons for each one, concatenating to a string that we then return.

Then in our index views, we just need to call this:

  <%=reorder_buttons @project %>

That generates exactly what I need - four buttons, one for each reordering action.

Wrapping Up

This solution easily allowed me to add reordering to a lot of controllers in only a few minutes. Hopefully it will help you do the same. You could improve this by storing the methods in a constant so that you didn't have to duplicate the array all the time, and I'm sure there are other improvements that I could make as well. I'd love to hear from you.

Making “as_string” Attribute Readers for ActiveRecord

Posted by Brian in Howto, Metaprogramming, Rails, tips (March 15th, 2010)

Occasionally, I need to transform boolean model attributes like “active” to display “active” or “inactive” instead of “true” or “false” when making reports or views. A lot of times this means writing some kind of helper method like this:

def active_or_inactive(object, true_message, false_message)
  object.active ? true_message : false_message
end

and calling it like this:

  <%= active_or_inactive(@project, "Active", "Inactive" %>

That’s not a bad approach, and it helps keep the views slightly cleaner by keeping the logic out, but it ends up being more characters than simply using a ternary operator in the view. I’ve used a slightly different approach in some of my more recent projects and I thought I should share it with you.

Move It To The Model

That’s right, I’m advocating pushing that helper into the model itself. I can hear you now, yelling something about “this guy doesn’t know what he’s talking about! How dare he put display logic in his models!” But before you close your browser, allow me to explain.

It just so happens that I need this logic not only in my views, but in my text-based reports that I run outside of the web server. I could mix the module with the helpers in when I needed it, but there’s also something un-object-oriented that bugs me about helpers. They remind me of PHP a bit. I feel like I should be calling object.active_as_string("Active", "Inactive") instead. So that’s what I’m going to do.

First, a unit test, because we’re all good professionals that write tests first. I want to call a method called active_as_string which takes two parameters – the string to print when it’s true and the string to print when it’s
false. Here are my tests:

require 'test_helper'

class ProjectTest < ActiveSupport::TestCase

  test "should display 'Active' if active" do
    p = Project.new(:active => true)
    assert_equal p.active_as_string("Active", "Inactive"), "Active"
  end

  test "should display 'Inactive' if not active" do
    p = Project.new(:active => false)
    assert_equal p.active_as_string("Active", "Inactive"), "Inactive"
  end
end

Tests help me design the method’s use up front. With two failing tests as my guide, I can now take my first stab at making the method work:

class Project < ActiveRecord::Base
   def active_as_string(true_message, false_message)
      self.active ? true_message : false_message
   end
end

With that implemented, my tests pass. However, I also have a "closed" boolean I need to handle, and it would also be nice if I could display "No description" if a project's description was blank. I could write my own _as_string methods like I've done already, but instead, I'll do a little metaprogramming to generate what I need.

Let's add four more test cases - to test the "closed" and the "description" fields.

  test "should display 'Closed' if closed" do
    p = Project.new(:closed => true)
    assert_equal p.closed_as_string("Closed", "Open"), "Closed"
  end

  test "should display 'Open ' if not closed" do
    p = Project.new(:active => false)
    assert_equal p.closed_as_string("Closed", "Open"), "Open"
  end
  
  test "should display 'No Description' if description is nil" do
    p = Project.new(:description => nil)
    assert_equal p.description_as_string("No Description"), "No Description"
  end

  test "should display the description if it exists" do
    p = Project.new(:description => "Hi there!")
    assert_equal p.description_as_string("No Description"), "Hi there!"
  end

Now, let's build some methods!

ActiveRecord::Base.columns

Every ActiveRecord class has a class method called columns that returns a collection of column objects. The Column object describes each database column and lets you determine its type and its name. We can use that and class_eval to generate a whole bunch of methods at runtime.


class Project < ActiveRecord::Base
  self.columns.each do |column|

    if column.type == :boolean

      class_eval <<-EOF

        def #{column.name}_as_string(t,f)
          value = self.#{column.name}
          value ? t : f
        end

      EOF

    end
  end
end

In this example, we're creating the _as_string method for each boolean column. It takes two parameters and is basically the same code we already used in our original method earlier. Notice how class_eval can do string interpolation using Ruby's #{} syntax. That makes it easy to build up the method names.

We can use that same concept to do the same for any other methods - we'll just cast them to strings and check to see if they are blank.

  class_eval <<-EOF

    def #{column.name}_as_string(default_value)
     value = self.#{column.name}.to_s
     value.blank? ? default_value : value
    end

  EOF

We throw that into the else block and our whole example looks like this:

  class Project < ActiveRecord::Base
  
    self.columns.each do |column|
    
      if column.type == :boolean
      
        class_eval <<-EOF
        
          def #{column.name}_as_string(t,f)
            value = self.#{column.name}
            value ? t : f
          end
          
        EOF
        
      else
      
      class_eval <<-EOF
      
          def #{column.name}_as_string(default_value)
           value = self.#{column.name}.to_s
           value.blank? ? default_value : value
          end
          
        EOF
        
      end
      
    end
  end

If you run your tests now, they all pass. But our work isn't done - this isn't very DRY. We may want to use this in another class too.

Modules!

Create a new module and mix the behavior into your models. Create the file lib/active_record/as_string_reader_methods.rb (create the active_recordfolder if it doesn't exist already) and put this code in the file:

  module ActiveRecord
    module AsStringReaderMethods
     def self.included(base)
       create_string_readers(base)
     end

     def self.create_string_readers(base)
      base.columns.each do |column|

         if column.type == :boolean

           class_eval <<-EOF

             def #{column.name}_as_string(t,f)
               value = self.#{column.name}
               value ? t : f
             end

           EOF
         else

           class_eval <<-EOF

             def #{column.name}_as_string(default_value)
               value = self.#{column.name}.to_s
               value.blank? ? default_value : value
             end

           EOF
         end
       end
     end
    end
  end

It's mostly the same code we had before, but in this case we're using the self.included method to trigger the method creation on the model that includes the module.

Now, remove the code from your Project mode and replace it with

include AsStringReaderMethods

Run your tests, and everything should pass. You now have a module you can drop into your projects and you'll have this functionality yourself. Now it's up to you to expand upon this, and use this pattern in your own work if you find it useful.

Good luck!

Basic Authentication in Ruby on Rails – In Case You Forgot

Posted by Brian in News (March 11th, 2010)

There are so many authentication choices in Rails these days, but sometimes the simplest approach is the best approach. I’m working with a client right now building an application that has a mostly-public interface. Only a handful of people need to log in to the site, and they only need to modify content occasionally. It’s not a complicated project at all, and while my first instinct was to reach for my starter project that I usually use for these kinds of things, I thought again and realized the following:

  1. This project doesn’t need to let people sign up.
  2. There’s no need to send password recovery instructions
  3. Much of the data entry will be done with a mobile device connecting to the app’s REST-style XML API.

Something like Authlogic, or even Restful Authentication seems like overkill for something this simple. Many Rails developers are probably used to their solutions because many Rails projects are more complex than this. In the spirit of keeping things simple, I’m going to show you how to do authentication of users without any plugins, the way we used to do it in 2005. (For those of you that have been working with Rails as long as me, this will be a good refresher for you. When was the last time you hand-rolled your authentication solution?)

Back To Basic (Authentication, that is)

Since Rails 2.0, Basic Authentication has been an option, as Ryan Bates explains in Railscast #82. We’ll use that and a basic user model to authenticate our users.

First, generate a user mode with login and a hashed password fields. I’m not going to do any salting here, as it’s not necessary. If you want it, you should be able to add it easily.

ruby script/generate model User login:string hashed_password:string

Now we need to modify the User model to do the password encryption.

First, set up the validations and the attribute accessors for the password and password_confirmation fields.

  validates_presence_of :login
  validates_confirmation_of :password
  attr_accessor :password

Next, be a good developer and write a unit test for hashing the password.

  test "should create a user with a hashed password" do
    u = User.create(:login => "homer",
                 :email =>"homer",
                 :password => "1234",
                 :password_confirmation => "1234")
    u.reload # (make sure it saved!)            
    assert_not_nil u.hashed_password
  end

Prepare your test database

rake db:test:clone

and run your test

rake test:units

With the test in place, write the code to encrypt the password on save. Add the SHA1 digest library at the top of your class:

require 'digest/sha1'

Then add the before filter and an encryption method:

  before_save :encrypt_password
 
  def encrypt_password
    unless self.password.blank?
      self.hashed_password = Digest::SHA1.hexdigest(self.password.to_s)
      self.password = nil
    end
    return true 
  end

Run your test again and everything should pass.

rake test:units

Authenticating Users

Now we need to write a class method that we can use to grab a user from the database by looking up their username and hashed password. We’ll use a simple pattern for this. First, let’s write a quick test:

  test "given a user named homer with a password of 1234, he should be authenticated with 'homer' and '1234' " do
    User.create(:login => "homer",
                 :email =>"homer",
                 :password => "1234",
                 :password_confirmation => "1234")
    assert User.authenticated?("homer", "1234")
  end

We create a user and then call User.authenticated?. If its return value evaluates to True, we’ve got a good set of credentials. Add this class method to your User model to make your test pass:

  def self.authenticated?(login, password)
    pwd = Digest::SHA1.hexdigest(password.to_s)
    User.find_by_login_and_hashed_password(login, pwd)
  end

Notice that here, I’m actually returning the user object, rather than a boolean. If no user is found, nil is returned which evaluates to false. Remember, in Ruby, everything except nil and false evaluates to True.

Our entire user model looks like this:

require 'digest/sha1'
class User < ActiveRecord::Base
  
  validates_presence_of :login
  validates_confirmation_of :password
  attr_accessor :password
  
  before_save :encrypt_password
  
  def self.authenticated?(login, password)
    pwd = Digest::SHA1.hexdigest(password.to_s)
    User.find_by_login_and_hashed_password(login, pwd)
  end
  
  private
  
  def encrypt_password
    unless self.password.blank?
      self.hashed_password = Digest::SHA1.hexdigest(self.password.to_s)
      self.password = nil
    end
    return true 
  end
end

Creating the Filter

Let's create a simple Projects scaffold. We'll use our authentication to protect this scaffolded interface.

ruby script/generate scaffold Project name:string description:text completed:boolean

Now, open app/controllers/application_controller.rb and this code:

  def authenticate_with_basic_auth
    authenticate_or_request_with_http_basic do |username, password|
      @current_user = User.authenticated?(username, password)
    end
  end

This tiny bit of code will pop up a Basic Authentication credentials box and look the user up in our database using the supplied credentials. If we find our user, we put it in the @current_user instance variable. It's common practice in Rails apps to have a current_user helper method, so we can add that to application_controller.rb as well.

  helper_method :current_user

  def current_user
    @current_user
  end

With that, we simply need to invoke the filter. Open your projects_controller.rb file and add this to the top:

before_filter :authenticate_with_basic_auth

And that's it! You've protected the application. Create a user via the Rails runner, fire up script/server and test it out!

ruby script/runner 'User.create(:login => "homer", :password => "1234", :password_confirmation => "1234")
ruby script/server

You should also be able to use cURL to play with the XML REST-style API provided by the scaffold generator.

Get projects:

curl http://localhost:3000/projects.xml -u homer:1234

Create project via XML

curl http://localhost:3000/projects.xml \
-u homer:1234 \
-X POST \
-d "Test" \
-H "Content-Type: text/xml"

Simple is Good

This simple solution is easy to write, easy to maintain, and easy to extend. It's also something that anyone with any practical experience with Rails should be able to write in as much time as it would take to configure Authlogic.

So what's left to do with this? First, SHA1 isn't great encryption - it's just hashing. BCrypt might be better, Adding a salt to this hash might be another good idea too. Some more tests would be great. So, go write them, make this fit your security needs, and have fun! As always, I'd love to hear your comments.

Rails and SQL Server – “There is no text for object”

Posted by Brian in Howto, Rails, tips (February 23rd, 2010)

I recently moved a Rails application to a new SQL Server 2005 server on a recent project and everything seemed to go smoothly, but when I tried to fire up a connection to the database from my Rails application, I was greeted with

ActiveRecord::StatementInvalid: DBI::DatabaseError: 42000 (15197) [FreeTDS][SQL Server]There is no text for object 'people'.: EXEC sp_helptext people

The “people” table here is actually a view that gets used all over the place in multiple applications. The DBA had moved the databases from an older SQL Server 2000 database previously.

The solution was to ensure that the application’s user account had the “view definition” permission on the view in question as well as the “select” permission. On the view, in the SQL Server Management Studio, right click and choose “Properties”. Then choose Permissions select your user account, and then select the “View definition” permission. Checking the box under the “Grant” column was enough for me to make it work.

Interestingly enough, the production server (which was upgraded months ago from SQL Server 2000 to 2005), does not have the permission set, but still works fine.

Hopefully someone else finds this useful.

Why Rails?

Posted by Brian in News, Rails (February 16th, 2010)

NAPCS was a proud sponsor of the first Chippewa Valley Ruby Camp, a day-long Ruby training camp where 23 students learned how to build and deploy their first Rails application. I taught two of the three sessions and had a great time helping other developers get their hands on what I believe to be the best way to develop scalable, maintainable, and stable web applications today. That’s a pretty bold statement, but I believe in it, and it’s why NAPCS uses Rails on all new client projects. (In fact, every project since 2006 has been a Rails project.)

Rails projects are quick to launch

With Rails, we can build and launch a prototype application in an extremely short time. On average, we can have something simple in front of the client in less than a couple of days, which is much faster than our previous projects where we used ASP or PHP. And that project isn’t usually a throwaway project; we can tweak it and move forward, from prototype to production.

Rails applications are easily testable

Professionals write tests that prove the code works as it should, and since testing is built right in to the Rails framework. testing is an easy natural part of the process. Testing has always been possible regardless of the language used, but with Rails, it’s so easy to produce well-tested code that you’d be foolish not to test. For my customers, that means much better products, and less support calls.

It’s a standard framework

I occasionally pick up projects from other developers, and while I can’t always ensure that the quality of the code will be good, I at least already know my way around the project because, in a Rails application, conventions dictate where things go. This means the learning curve is lower when we transition an application, and the customer doesn’t get billed extra time for me to figure out what’s going on.

The community is incredible

We rely heavily on open-source projects to get stuff done, and Rails has an amazing community that is always pushing the limits of what Rails applications can do. There is a new solution to a new problem almost every day, and that keeps us all on our toes. Plus, we’re very proud to be sponsoring the Rails Mentors project, which helps other developers get better at Rails development. We’re always giving back to open source, too.

It gets out of the way.

This is the most important point of all; Rails lets me deliver features. Instead of spending hours wiring up database tables to web pages, I can do that in five minutes and spend more time focusing on user experience and new features. And since it isn’t difficult to build things incrementally, I don’t get boxed in. I can make changes without feeling that I’ll lose days of work. It allows me to respond flexibly to new feature requests.

Rails gives us a competitive advantage. We cannot always compete on price alone, but we can provide better-quality solutions than others because we embrace an open, agile framework that lets us deliver stable, scalable, well-tested, and maintainable web applications.

Want to learn how you can take advantage of Ruby on Rails?

Contact us for information on customized training and mentoring services. We offer affordable hourly rates for remote mentoring, as well as custom training classes upon request.

Moving from Prototype to JQuery

Posted by Brian in tips, web (November 15th, 2009)

On a recent project, I converted a ton of Javascript from Prototype to jQuery in order to take advantage of many of the nice UI elements available. As I did the conversion, I took down some notes that I wanted to share with you about the differences between the two libraries. In some cases, the differences are insignificant, and in a couple of others, the differences merely come down to a difference of opinion among the developers and supporters of the libraries.

Here are the notes:

Getting Ready

Before you can work with elements on the page, those elements must be loaded.

Prototype uses

document.observe("dom:loaded", function() {
  // your functions
})

jQuery uses this:

$(document).ready(function(){
  // your functions
})

Finding things

In Prototype, you use $() or $$() to locate elements. With $() you use the ID, whereas with $$() you use a CSS selector.

  var header = $("header");  // a single element, 

With JQuery, you do almost all of your element location using $(), which works very much like $$() in Prototype.

  var header = $("#header");  // a single element, 

Binding events

Prototype’s Element class has an Observe method. It’s very easy to use and easy on the eyes.

  $("header").observe("click", function(event){
    alert("Hi there");
  });

In jQuery, it’s nearly identical, except that click is a method on the JQuery object.

  $("#header").click(function(event){
    alert("Hi there");
  });

At first, the differences look marginal, but let’s look at a more complicated example:

In Prototype, to find all links on the page with the class “Popup” and make them open in a new window, you have to do this:

function new_window_links(){
  links = $$("a.popup");
  links.each(function(link){
    link.observe("click", function(event){
      window.open(link.href);
      event.stop();
    });
  });
}

The Prototype version makes us find all of the elements, loop over them, and then apply the observer to each one.

jQuery can hide the iteration from you, which results in somewhat cleaner code.

function new_window_links(){
  links = $("a.popup").click(function(event){
      window.open($(this).attr('href'));
      event.preventDefault();
  });
}

Adding Classes

Prototype:

   $(".foo").addClassName("ninja");
  $(".foo").addClass("ninja");

Traversing the DOM

Prototype:

  parent_of_foo = $("foo").up();

jQuery

  parent_of_foo = $("#foo").parent();

Working with HTML attributes

This one was the most difficult to get used to. In Prototype, many of the HTML attributes are available as methods on the Element class.

  window.open(link.href);

In jQuery, you use the attr method to get and set the attributes.

  window.open(link.attr("http");

This illustrates only a few of the differences between the libraries, but as you can see, the differences don’t realy amount to anything substantial. Both of these libraries greatly simplify cross-browser JavaScript development, so no matter which you choose, you’ll be in good shape.

Chippewa Valley Code Camp 2009

Posted by Brian in News (November 15th, 2009)

I had the honor of presenting two talks this year at the second annual Chippewa Valley Code Camp. Code camps are free events where programmers of any skill level come together for a day of sessions and talks that are centered around code. I’ve only recently become involved with these events and am extremely happy I have. The opportunity to learn from so many experienced developers is incredible.

We held the event at UW-Stout this year, and had a great turnout. I gave two talks, the first on Ruby, and the second on Cucumber. I had wonderful audiences both times, and met some great people that I hope I get to work with in the future. Here are the slides for my talks.

See the end of the slide decks for links to the demo source code.

« Previous PageNext Page »