Archive for the ‘Programming’ category

Blurry Fonts on External Monitor with MacBook Pro

August 29th, 2010

I don’t know if you have the same problem as me, but when I plug my MacBook Pro into my HP w2338h monitor the fonts are not as crisp as on the laptop itself.  I found out that there’s a bug in how Mac OS X detects whether it should use font smoothing or not for certain external monitors. It’s not a problem if you’re using an Apple monitor (obviously their stuff works perfectly with their own stuff), but not all of us as so fortunate to shell out that kind of cash.

You can easily fix this by typing the following into your command line:

defaults -currentHost write -globalDomain AppleFontSmoothing -int 2

 

You can try int 1 to 3 (to play with various levels of font smoothing, I found 2 to work best for me).  To remove the setting just open the Appearance app (inside the Control Panel) and at the bottom you’ll see LCD font smoothing with a [-] inside, click it off and back on and it’ll show up as an [x] (and you’ll be back to where you started).

You may have to quit and restart your application before you see the effect.  I tested it out using my terminal application since that’s something I use quite a lot and not having nice smooth fonts in it makes me cry. 

Below are two screen shots to demonstrate the difference.  Notice how the first image shows 3 columns of text, while the second only two.  This is because in the first screen shot (with no font-smoothing) the fonts take up just a few pixels less space, as smoothing adds a few pixels to each font to fill them out so they’re more readable on an LCD screen.

before tweaking fonts appear incomplete and with fuzzy edges

Before tweaking fonts appear incomplete and with fuzzy edges.

The screenshot below matches what I normally see on my montior’s laptop. Fonts are bold and character are filled out fully (no fuzzy edges, offsets or bleeding).

after tweaking the fonts are properly smoothed on my external monitor

After tweaking the fonts are properly smoothed on my external monitor.


LSRC 2010 – Day 2

August 28th, 2010

Below are my notes from the second day at LSRC.

Faster Test Suites

Nick Gauthier gave an impressive talk on reducing the execution time of a test suite.  The original suite took over 15 minutes to run.  Using factory_girl, shoulda and paperclip, he strongly recommended empty DB testing (no fixtures, all tests setup and tear down their objects/records), and the use of “no side-effect” test blocks.

Switching to the use of fast_context the execution time was brought down to 5 minutes.  Using perf_tools he found that calls to ImageMagic (from Paperclip) were calling out to the shell, taking a lot of time.  So he mocked those calls and brought it down to 3 minutes.

Using Hydra to do multi-core (concurrent) testing he brought execution time down to 1 minute.

Hydra is easy to set-up (no sockets or daemons to configure).  Just add a Rake task and configuration yml and you’re ready to use it.

When you run Test::Unit the Rails environment is loaded 4 times!!  Cucumber loads the environment twice.  RSpec and Hydra load it just once.

Further tweaking EXT4 journal_data_writeback and atime (access time) on the file system he got testing down to just 50 seconds.  Using Ruby Enterprise Edition (with the tmalloc) and more tweaks (this time to the Ruby _HEAP and _GC settings) he had tests running in 18 seconds.  A 4417% increase in performance!!

Check the comments below for a link to Nick’s presentation slides.  He’s been kind enough to provide the link!

Searchability

Luigi Montanez gave an insightful presentation on SEO.  He doesn’t believe that you have to be an “expert” in SEO.  You simply need to have good content and Google (or Bing) will handle the rest.  There are some things you can do though to make sure you don’t sabotage your pages when crawlers visit them.

Make sure you have a sitemap.xml (sitemaps.org) and a robots.txt (robotstxt.org).  These help crawlers know what to pay attention to and what to ignore.  Make sure you use either a www or non-www domain.  If you have both choose one and redirect to it.  You don’t want to have the site indexed under both.

When redirecting make sure you use 302 and 301 appropriately.  302 is for a temporary redirect, and Google/Bing will not index the page it’s redirected to.  Use 301 instead, if your intention is to have the page permanently moved.  Be cautious too because many web frameworks will use a 302 by default, instead of a 301.

Do not change your content by region, nor require cookies for someone to view content.  Also page titles are very important.  Always follow the “Page Title | Site Title” style (or you can replace | with a – or some other delimiter, just be consistent).

In your URLs dashes (-) are word separators, underscores (_) are not!  Make sure you are using dashes in your URLs!!  Take advantage of meta tagging, and Google Webmaster Tools.

Takeaway:

  • Think like a searcher (search engine: crawler, index, rank)
  • Optimize your title tags (they are the most important thing)
  • Use Google Webmaster Tools (it provides valuable insight)

Components

Nick Sutterer gave a cool demonstration of Cells and Apotomo.  They allow you to create stateful widgets in your Rails views.

Padrino

Joshua Hull gave a talk on Padrino, another web framework built on top of Sinatra.  It takes a minimalist style approach (take what you need).  It’s light-weight and fast.  It has all the basic stuff you’d expect of  web framework including a simple mailer.

The Elegance of Ruby

August 28th, 2010

Take this simple example of sorting an array of names in Java vs. Ruby:

// in Java with import java.util.*; (so we can use the sort method)
String names[] = {"Nicholas", "Calvin", "Tank", "Karen", "Amanda"};
Arrays.sort(names);
System.out.println("The names sorted:");
for (int dex = 0; dex < names.length; dex++) {
    System.out.println(dex + ":" + names[dex]);
}

# in Ruby
names = %w(Nicholas Calvin Tank Karen Amanda)
names.sort.each_with_index { |x, idx| puts "#{idx}:#{x}" }

0:Amanda
1:Calvin
2:Karen
3:Nicholas
4:Tank


Both produce the same output, but Ruby handles Array and enumeration a lot better imho. The code is simpler and you don’t have to deal with silly for loops or include any special utility libraries.

LSRC 2010 – Day 1

August 27th, 2010

Had a great info-filled day today at LSRC.  It’s my 3rd year attending.  Below are some of the highlights of the different talks I attended:

Real Software Engineering

Glenn Vanderburg gave a great opening talk about software engineering.  he said software engineering doesn’t work.  He explores the roots of the idea of “software engineering” all the back to the first NATO Software Engineering Conference on the subject.  At the conference they described best practices as:

  1. A software system is best designed if tests are interlaced with the software as it’s developed, rather than at the end.
  2. Creates a simulation which matches the requirements, contains the control which organizes the design of the system.
  3. Through successive repetitions of testing and design, the model ultimately becomes the software system itself.

Sound familiar?  He then talks about what went wrong, how did we start with what sounds like Agile and ended up with waterfall.  He talked about how the creator of waterfall process (Winston W. Royce) actually was trying to express he didn’t feel it worked.  His paper was so poorly written though that people (paying attention mostly to the fancy diagrams, and not the text) believed he was in favor of it.

Cost is *always* an object, and engineering is about what you can do with a dollar vs. what a “bumbler” can do with two.  Mathematical models are not supposed to be about correctness, but about saving on costs.  In traditional engineering you create models because it’s expensive to use up materials, labor, etc.  In software these things are extremely cheap and expendable, so mathematical models are less important.

Engineering is a science AND art.  It involves designing AND making, with cost AND elegance balanced.

Don’t build software as if it were bridges.  The source code *is* the design!  Customers are not paying for the source code.  It is the design of the software system.  Programs themselves are the models.  The customer in the end desires working software.

How to Build Awesome Teams

The guys from Hashrocket talked about their hiring process and what they felt made for great teams, core ideas:

  • Hiring
  • Transparency
  • Community
  • Methodology
  • Environment

They frown on:

  • Micro-management
  • Penny pinching (they still budget)
  • Death marches
  • Meetings (daily stand-up, monthly mission control)
  • Hierarchy
  • Future-proofing

When they hire candidates they look for people who are smart and get things done.  They look for individuals who like to communicate, participate and contribute back to the community.  They need to be a cultural fit.  They look at their online presence, see what they’re Twittering about, review their work on GitHub (code, commit hygiene, etc).  They also require a candidate to subject themselves to a week long interview, where they pair program and go to after-hours with the team.

Keynote: Tom Preston-Werner (GitHub)

Today everyone can start a business on their computer.  What you need though is an idea.

  • go to user groups (learn about people’s problems)
  • drink (seriously, it makes you honest)
  • find people you can work with (co-founders)
  • build something you love (that inspires you)
  • look for untapped potential (who are the early adopters, and how awesome can it become?)
  • keep your day job (not having time is a poor excuse)
  • fight entropy (keep it simple, and get stuff done)
  • ship it (or you might as well not exist) [ship it squirrel]
  • charge money (investors only care about money, not your company, so make customers your investors)
  • have fun! (“drink-ups” where drinking is sponsored)
  • never give it up (it’s going to be hard, don’t let fear hold you back)

If you want to have a $100,000 a year salary, you just need to get about 500 subscriptions at $12/mo (with a few premium or mid-level price options).  It’s totally realistic and in your grasp.  Don’t be afraid of not knowing something … people just like you started out with just an idea.

Compile Your Own VIM

August 22nd, 2010

VIM is a powerful text editor that is available across all platforms.  While TextMate is awesome for MacOS X, no question, not all of us can work in TextMate 100% of the time.  (For example, at work I have to use a Linux desktop system to develop my code, no TextMate for me.)  I personally find it easiest to just focus on getting very familiar with one text editor, rather than constantly switch contexts, so I stick with VIM (since it’s available anywhere).

Getting and Configuring VIM

You can compile your own version of VIM (this is recommended) to make sure you have all the features and you can include Ruby Interpreter support by using [you can use CURL  or even just a ftp or web browser to get the archive, you may also need to run the make install as sudo unless you are already root]:

mkdir src
cd src
wget ftp://ftp.vim.org/pub/vim/unix/vim-7.3.tar.bz2
./configure --with-features=huge --enable-cscope --enable-rubyinterp
make
make install



Unless you’re on a wimpy system you’ll want to do nothing less than huge.  This will install vim and related files to /usr/local/bin (unless you specified otherwise when configuring).

Additional Information

PeepCode has some great videos on how to use VIM, for sale.  You can also a find some good ones on YouTube that are free, but your time/mileage may vary.

Tim Pope also maintains a great collection of VIM plugins that are useful for Ruby/Rails developers.


Rollback with Yum History

July 8th, 2010

Ever want to install software and find out your missing libraries? So you go and install all the libraries and dependencies.  Then afterwards you decide you don’t want the software after all. You’ve installed megabytes worth of packages and dependencies.  You want to get back to your previous state, but are not quite sure what needs to be removed. Now what do you do? You can’t remember what was installed or all the dependencies that came with those packages, but you roughly remember the day and time you played around with the new software.

This is where yum history comes to the rescue.  (If you’re using a RPM friendly flavor of Linux, like Fedora or RedHat). You can get a history of what was installed by using

$> sudo yum history

Loaded plugins: presto, refresh-packagekit
ID | Login user      | Date and time    | Action(s) | Altered
---------------------------------------------------------------
47 | System <unset>  | 2010-07-08 11:54 | Update    |   11   
46 | <nicholas>      | 2010-07-07 22:53 | Update    |    2   
45 | <nicholas>      | 2010-07-07 22:50 | Install   |   49
44 | <nicholas>      | 2010-07-03 18:52 | Install   |    8
...more

You can then find out what was installed that day and remove it:

$> sudo yum history undo 45

Fixing Rails 3 Beta ‘Invalid .gemspec format’ Errors

February 7th, 2010

If you’ve tried out Rails 3 on Ruby 1.9.1 (like myself) you might of noticed that a lot of errors are being sent to stderr, it’ll look something like this:

Ozawa Sakuro has posted a fix for this on GitHub.  You can see the original thread here, or simply follow the directions below to quickly fix it without trolling through the entire discussion:

1.  Edit lib/bundler.rb:

4: require 'bundler/rubygems-ext'  # originally 'bundler/rubygems'

2. Next rename lib/bundler/rubygems.rb to rubygems-ext.rb and then edit the file and wrap the require in a control structure as shown below:

1: unless defined? Gem
2:   require 'rubygems'
3:   require 'rubygems/specification'
4: end

I’ve tested this fix and it works with Bundler 0.9.3.  Version 0.9.4 resolves the issue (thanks for the update Christian).  In any event I hope this little nugget of information helps reduce the hair pulling.

Writing a Cucumber Feature

January 2nd, 2010

This is the second post about Cucumber, where we’ll be exploring the creation of a feature. Cucumber centers on testing the expected behavior of your application, rather than the expected behavior of a method. I had someone explain to me once, “unit tests/specs are the methods/implementation you wish you had, Cucumber tests are the application you wish you had.”

User Stories

When thinking about a Cucumber feature you will want to relate it to a user story. If you’re familiar with Agile development stories are nothing new.  For those who are not though it’s not too complicated. A story is simply an expression of value generally in the form of:  ”As {a role} I want/need {to do some function} so that {business value}.” Generally the business value is best expressed in terms of: revenue generation, revenue protection, operational efficiency (cost savings).

For the example we’ll be using this story:

As a workshop co-ordinator I need to manage contact information so I can easily reference individuals and start communications with them.

You’ll notice that this story doesn’t imply implementation.  You generally never want to imply implementation in a story.  Also you’ll notice that the story is simple and comprehensible by pretty much anyone (business user, developer, average Joe Public).

Starting a Feature File

In our Rails application we’ll want to go inside our /features folder.  Create a new file called manage_contact.feature.  At the top of the file type in the following:

Feature:  Manage Contact
  In order to easily reference individuals and start communications with them
  As a workshop co-ordinator
  I want to manage contact information

Now we have our first feature.  The next step is to define some scenarios.  Scenarios express various actions the user might take in relation to the feature.  Below are some of the scenarios we came up with for this feature (these go below your feature entry – indented to be even to the “In order, As a, I want” section).  You don’t need to, but I like listing the scenarios in order of priority, this way a developer working on the feature can just start on top and work downwards:

Scenario: View list of contacts

Scenario: Add a new contact

Scenario: Email a contact from the list

Scenario: Remove an existing contact

Scenario: Update an existing contact

Scenario: Start an IM conversation with a contact from the list

Your finished feature file should look something like this gist. In the next post we’ll start to look at building out our scenario’s with step definitions, that is define what behavior we expect to happen with each scenario we have defined.

Adding Cucumber to Your Salad

January 2nd, 2010

Cucumber has come a long way since I’ve first started to use it.  My two posts about getting started with BDD have been the most visited pages of my blog.  So it seems only fitting to address the new features and update the material.  I’ll be creating a series of blog posts (so it doesn’t end up being one giant scrolling page) addressing a real-life situation of creating a contact management feature.  We’ll build it from the ground up using Cucumber and RSpec.

Installing Cucumber / RSpec

The first step to using Cucumber (and RSpec) is to install the necessary gems.  This is very straightforward and probably familiar to most people:

sudo gem install rspec rspec-rails cucumber cucumber-rails webrat ZenTest database_cleaner

If you are using Ruby > 1.9 you will also need to install the test-unit gem (or RSpec will not load properly).

sudo gem install test-unit -v=1.2.3

Now if you run into errors installing webrat, know that it requires nokogiri (an awesome XML parser, see my blog post about nokogiri).  In order to build nokogiri though you need to have a few libraries installed ahead of time.  If you run into any errors installing webrat (likely because it couldn’t install the dependency nokogiri gem) try the following (I’m using a Debian -Kbuntu- flavor of Linux, so your specific command might vary):

sudo aptitude install libxml2-dev libxslt1-dev

Once you have installed the two developer libraries for libxml2 and libxslt you can try to reinstall webrat (sudo gem install webrat) and it should properly build.

Adding RSpec and Cucumber to a Rails Project

Having the gems installed is the first step.  To use Cucumber in your Rails project you need to run a few generation scripts which prime your application and make a few config updates. Run the following commands from inside your Rails application root:

script/generate rspec
script/generate cucumber

These scripts create new rake tasks, a spec and feature folder, as well as modify your database.yml (adding a new cucumber environment).  You’ll also notice a new cucumber environment file added to your environments folder already completed with all the necessary config.gem entries, nice.

That’s all there is to it for getting started.  Next post I will talk about outside-in development and starting your first feature!

Rails on Windows with JRuby

December 12th, 2009

Getting a working Rails stack on Windows can be a frustrating experience.  Rails was born in the Linux/Unix world so there are many libraries assumed to be on your system, but are not part of a regular Windows OS installation.  Below I share my own personal experience with getting up and running with Ruby and Rails using JRuby, which for me was the best way to go.

Requirements

Note the links above might move or change so you can visit (java.sun.comwww.jruby.org, www.postgres.com) and poke around to find them.

Installing Java and JRuby

This part is very easy.  Just double click the Java installer and follow the directions.  It will install Java to a location in your C:\Program Files (or the location you specify).  Do the same with JRuby.  I like to have JRuby live right under C:\jruby-1.4.0 so it is easy for me to get to (by default it will also go under C:\Program Files).

Now we need to edit our Windows environment and make sure that JRuby and Java can be seen on the path.  You’ll want to go to your Start > Control Panel > System > Advanced system settings and click the Environment Variables button.

Windows Environment VariablesYou might already see a JAVA_HOME value under User variables (and that’s ok).  You might even see one for JRUBY too.  I like to have the environment variables for Java and JRuby available at the system level however.

Click New under the System variables section and add entries for JDK_HOME and JRUBY_HOME as you see in the example on the right.  Click OK when you’re done.

Now open a command prompt window (Start > Accessories > Command prompt) and type in echo %JDK_HOME% and hit enter.  You should see the value you set, do this for (echo %JRUBY_HOME%) as well. Both should return the values you set previously in the Environment Variables window.  The last thing to do is add these values to your PATH.

Return to the Environment Variables window and edit the PATH value under system variables by selecting it and hitting Edit.  Entries are separated by a semi-colon (;) so make sure you add one to the front of the entries you’re adding unless there is one already there:

;%JDK_HOME%;%JRUBY_HOME%

Now after that’s done close and reopen your command prompt window (so that the new values are loaded).  Type echo %PATH% and you should see the two paths at the end of the results:

>> echo %PATH%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;
C:\Windows\System32\WindowsPowerShell\v1.0\;
C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files(x86)\Git\cmd;
C:\Program Files\Java\jdk1.6.0_17;C:\jruby-1.4.0\bin

Now that all our paths seem in order we can further verify everything is working right:

>> java -version
java version "1.6.0_17"
Java(TM) SE Runtime Environment (build 1.6.0_17-b04)
Java HotSpot(TM) 64-Bit Server VM (build 14.3-b01, mixed mode)
>> jruby -v
jruby 1.4.0 (ruby 1.8.7 patchlevel 174) (2009-11-02) (Java HotSpot(TM) 64-Bit)

Welcome to JRuby

At this stage you should have a working copy of JRuby.  JRuby is just like Ruby, except it uses Java and not the MRI/YARV interpreter.  Most of the commands you might be used to on a regular Ruby stack work the same in JRuby, except often you use jruby -S to run your commands rather than ruby.  Let’s start installing a few of my favorite gems:

jruby -S gem install rails haml nokogiri shoulda factory_girl cucumber webrat ^
rspec rspec-rails will_paginate ZenTest redgreen fastercsv RedCloth paperclip ^ 
nifty-generators jruby-openssl

That should be plenty to get you going on most any Rails/Ruby project.  Watch the output as the gems are installed, rarely should you run into trouble.  If a gem is complaining about installing you can add the –platform=java flag to the end to try and force it to install under the Java platform (for example):

>> jruby -S gem install grumpy_gem --platform=java

Connecting to Postgres

You probably can use any Rails supported database, but I prefer Postgres.  It’s a free database that is available on a variety of platforms (much like MySQL) but a little more powerful.  I also find it easier to work with on JRuby so it’s the one I’ll use here.

Run the PostgreSQL installer.  Follow the on-screen directions.  During the installation, however it is important to make sure you install the optional JDBC drivers, don’t forget this step (if you do you will have to run the Postgres Stackbuilder application later and install them).

The installer is going to add a ‘postgres’ user onto your system and require you to restart at some point.  Once the installation is completely finished you can open your command prompt and install the Rubygem for connecting to Postgres:

>> jruby -S gem install activerecord-jdbcpostgresql-adapter

I am not going to go into details about how to set-up users, etc. in Postgres.  You hopefully are familiar enough with database software to know how to do there is plenty of information on the Web to figure this out, just Google it.  Postgres comes with some nice GUI tools that make it easy to do and it is pretty straight forward.

Now there is one caveat with the Postgres ActiveRecord adapters and JRuby.  There’s a known issue with creating and dropping databases in Rails.  So in order to get things like rake db:create:all to work you need to type inside your Rails application root:

>> jruby -S script/generate jdbc

That is pretty much all there is to getting a full stack up and running on Windows.  I have started developing in the past week using JRuby on Windows along with Rubymine as my editor and GIT as my source control.  I’ve been pretty happy with it thus far.  I still enjoy developing most on my MacBook Pro – but it was a fun experience exploring JRuby (I’ve been playing with JRuby and Ant working together).

4-Bit Server VM 1.6.0_17) [amd64-java]C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\Wind
owsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files
(x86)\Git\cmd;C:\Program Files\Java\jdk1.6.0_17;C:\jruby-1.4.0\C:\Users\Nicholas>echo %PATH%
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\Wind
owsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files
(x86)\Git\cmd;C:\Program Files\Java\jdk1.6.0_17;C:\jruby-1.4.0\bin