July 28th, 2010

Rails 3: Reset your Javascript include defaults

Back in the olden days of May 2010 if you wanted to change your default Javascript files in Rails you did something like what Rizwan Reza describes here (http://www.railsinside.com/tips/451-howto-unobtrusive-javascript-with-rails-3.html). However, in upgrading a side project to the latest Rails 3 release candidate (from Rails3b4, fwiw) there is a better way.

The post linked above uses the following code:

However, as of the date of this posting (7/28/2010) it appears this approach has been deprecated in favor of register_javascript_expansion (http://apidock.com).

I likey.

The above example should now be:

Boom.

Notice in the latter approach the inclusion of “application.js” in the expansion array. Don’t forget that one.

Simply add javascript_include_tag :your_new_default to my layout, and you’re ready to go.

December 9th, 2009

Extend has_many with the :extend option

The method has_many has several options that help you refine an association. The :extend option is one that I found myself using recently, and thought it would be nice to share with the internet.

Say you have a Friendship class that belongs to a User class, and that your User class has_many :friends, :through => :friendships. A good old fashioned @user.friends would return all the user records for @user’s friends.

Let’s also say your friendships table contains the fields user_id:integer, friend_id:integer, and state:string, where state can either be ‘active’, ‘requested’, or ‘pending’.

You might be tempted to do something like this in your User class:
has_many :friends do
def active
...some query...
end
...and so on for each state
end

I suppose, this would be fine if you only needed one method. You need something for each state, though, and this direction leads to unsightliness quite fast. Enter :extend.

Using this method, you can define methods in a module and call that module using extend. So the association looks like this:
has_many :friends, :through => :friendships, :extend => FriendshipState

FriendshipState is the module where your methods are defined:
module FriendshipState
Order = "users.last_name asc, users.first_name desc"
def pending
find(:all, :conditions => ['friendships.state = ?', 'pending'], : order => Order)
end
def requested
find(:all, :conditions => ['friendships.state = ?','requested'], : order => Order)
end
def active
find(:all, :conditions => ['friendships.state = ?','active'], : order => Order)
end
end

NOTE: there should be no space between ‘:’ and ‘order’. I did that to prevent god forsaken emoticons

The join is handled for you, so @user.friends.active returns all user records for @user’s active friendships; and so on with pending and requested.

SELECT `users`.* FROM `users` INNER JOIN `friendships` ON `users`.id = `friendships`.friend_id WHERE ((`friendships`.user_id = 1) AND (friendships.state = 'active')) ORDER BY users.last_name asc, users.first_name desc

Nice, huh?

November 14th, 2009

Simple Two Way Encryption for Ruby on Rails

There are many options to choose from when you need to store an encrypted value in a database. After trying a few, I recently settled on Sean Huber’s delightful attr_encrypted gem.

To use attr_encrypted you’ll need to first install the gem (gem install shuber-attr_encrypted --source http://gems.github.com), then either require it in your class or via config.gem. I’ll demonstrate how to use attr_encrypted with a User record that, for whatever reason, needs to store the users Social Security Number (SSN).

Starting from scratch, let’s generate a User model with columns for the users name and encrypted SSN:

script/generate model User name:string encrypted_ssn:string.

You probably noticed that I created the column encrypted_ssn rather than ssn. This is because attr_encrypted expects the attribute you want to encrypt to be titled encrypted_#{attribute}. I’ll show you how to manipulate this in a moment.

Let’s encrypt the users SSN by calling attr_encrypted in our User model:

class User < ActiveRecord::Base
require 'attr_encrypted' #if you aren't using config.gem
attr_accessible :name, :ssn
attr_encrypted :ssn, :key => "some_key_you_like"

Be sure to declare :ssn in both your mass-assignment allowance and your encrypted attributes. Otherwise, you will get the famous “can’t mass assign…” warning in your log, or if you are validating presence of any encrypted attributes you will receive an error that they are blank.

From here, feel free to proceed as normal. Save the users SSN to the database from a form using the :ssn method, not the :encrypted_ssn method (text_field_tag 'ssn'). This will save the encrypted SSN to your db. Calling @user.ssn will yield the users decrypted SSN.

A Couple Extras

Pass the :attribute option to attr_encrypted if you would like the column to be something other than encrypted_#{attribute}.

attr_encrypted :ssn, :key => "some_key", :attribute => "private_ssn"

You will probably need to make sure that the SSN is unique, yes? In this case you want to validate the encrypted value:

validates_uniqueness_of :encrypted_ssn

As long as you are encrypting every SSN record with the same :key this will validate properly. Cover your bases and add a unique index on encrypted_ssn in your database, also.

attr_encrypted offers quite a bit more functionality, such as custom encryptors, custom algorithms, default options and marshaling. Be sure to read through the documentation at github.com/shuber/attr_encrypted.

Finally, thanks to Sean for helping me clear up a few things in my own use. He’s quite accessible.

June 7th, 2009

Make .bashrc Work for You with Aliases

fts-unix-frontQuick disclaimer, I’m no command line guru, but I am a huge fan of anything that helps me do my job faster, so I decided to load up some aliases in .bashrc this morning. A perfectly good Sunday morning activity.

I quickly ran in to a problem, though. My aliases weren’t working. The only way I could get them to work was to run source .bashrc. Logging out of Terminal didn’t do me any good, and setting a Terminal startup preference to run source .bashrc only worked for the first new window. Drag. So, to the Google Machine I went.

A simple search for Terminal doesn’t recognize .bashrc returned a helpful thread from macosxhints.com. A quick look at all the files in my home directory revealed no .bash_profile file. Aha! All I needed to do was create that file then add if [ -f ~/.bashrc ]; then . ~/.bashrc; fi and voila, problem solved. Update: After I tried to fire up a Rails project I realized that I should have modified .bash_login on my machine. The mix up caused a little problem where my version of RubyGems wasn’t being found. If you have .bash_login, add the aforementioned line there.

Now I can alias to my hearts content. I like to alias my ssh commands and other common directories that I frequently work from. Below are a few examples of popular aliases as well as how to use alias.

How to:

alias newcommand=”commandToBeExecuted”

Examples:

alias ll=”ls -ltr” #lists, in long form, non-hidden files in reverse order according to most recently modified

alias lf=”ls -F” #returns a file listing with / at the end of directories and @ at the end of symbolic links

alias l=”ls -al” #lists, in long form, all files, even hidden dot files, in long form

alias rm=”rm -i” #this command will prompt you when you attempt to remove a file

As I mentioned, I like to create aliases for quick access to directories I frequent. For example, when I fire up GoComics locally I use the following alias:

alias gc=”cd ~/path/to/gocomics/” #this gets me there no matter where I am in the files.

For more on alias check out http://www.itworld.com/operating-systems/59407/handy-dandy-aliases.

June 5th, 2009

A Developers Responsibility

UCLICK GoComicsWhen I was interviewing at UCLICK one interviewer said to me, In the end, it’s only comics. At the time, that put me at ease. I had just been introduced to programming and was nervous that I would somehow destroy the entire company by writing some errant code. Some years, a GoComics.com rebuild, and a GoComics.com relaunch later I believe that statement is far from true.

We just relaunched GoComics.com with a significant facelift as well as some really tasty goodness under the hood. One thing we recognized in the previous release of GoComics was that people were using the comments more as a meeting place. We decided to encourage that activity by creating more opportunities for people to comment. Another thing we did was add more sharing opportunities. Somewhat to my surprise, GoComic’s Twitter traffic has skyrocketed. Both of these features are evidence that GoComics isn’t only comics, it’s a community. People show up for the comics, but they stay for the camaraderie and are compelled to share what they find across the Internet.

Internally we built a page that lists every comment in real time. It’s fascinating to see what people are talking about. Everything from the mundane – what’s on the dinner menu for the evening – to the profound – a woman’s miscarriage experience and how it affected her feelings on abortion. Of course, there are trolls and troublemakers, but that’s any community. It’s great to watch how people handle them as well. Some get flamed, as would be expected, others are given the benefit of the doubt.

I think in the development process it’s very easy for the developer to lose site of the humanity of the project. You may be developing another entertainment/commerce/management/accounting/whatever application, but the truth is you are creating something for people. Ideally, real people are going to use what you create. For me, there’s a lot of weight in that realization.

The difficulty is in balancing this reality with the ever looming deadline. Whether you are contracting or employed by a company, you’ve, no doubt, got a deadline on your current project. The struggle becomes make it work versus make it work right. There is room for both. I’ve made it my focus to learn best practices, to not be embarrassed to ask, and to learn something new, no matter how minute, everyday. My goal is that this balance will become second nature. Lofty? Perhaps, but certainly attainable.

It is a real honor when something you contributed to becomes important to someone else. I’m proud of the work we’ve done with GoComics. So much of what was done will never be noticed by anyone but those of us that did the work and that’s alright. Active participation may be the highest form of appreciation.

February 5th, 2009

Annoy Your Friends With Emoji for Free & Without Jailbreaking Your iPhone

It’s easy and free to unlock Emoji icons for your iPhone with out spending $.99 or jailbreaking your iPhone. This method works with version 2.2.1 for your iPhone.

Spell Number in iTunes App Store

First, in the iTunes App Store download Spell Number (iTunes link). If you downloaded the app to iTunes, then you need to sync your iPhone to install the app on the device.

Spell Number application on the iPhone

Next, on your iPhone launch Spell Number. In the entry box enter 9876543.21 91929394.59. Then, close the application.

Read the rest of this entry »

February 4th, 2009

Thoughts About My Dad and the Last 25 Years

I was eight-and-three-quarters years old in 1985 when my family moved from West Palm Beach, FL to Kansas City, MO. My Dad had accepted a job with Bott Broadcasting. All I knew was that my grandparents lived in Kansas City. So, I packed up my GI Joes, Star Wars figures, my brown Fisher Price tape player, my Thriller cassette, and said good-bye to my childhood best friend, Tommy Hahn. Two months to the day that my Dad started Dick Bott, himself, fired my Dad. He gave him no severance and told him he didn’t have what it took to be in radio.

We had left behind a brand new house in Florida that wasn’t selling. The mortgage was quickly depleting what savings my Mom and Dad had. For the next year Dad did odd jobs to make ends meet. I remember delivering phone books with him one weekend for what I assume earned less than $25. Pretty soon, boxes of food and clothes started appearing on our front stoop every Saturday morning. I put it all together. We had nothing.

We rented a duplex from a Hindu family. Early one evening they showed up at our door with their children who were my age. I heard them tell my parents they had decided we should stay in their duplex for as long as we needed because they knew we were “good and Christian people.” That moment constantly challenges my faith and learned belief that Heaven is reserved for Christians. It was in that duplex that I remember my Dad bounding up the stairs after a day of job hunting laughing and exclaiming in relief and disbelief, “I got the job! I got the job!”

Read the rest of this entry »

January 14th, 2009

Growing Up Star Wars Is Stellar

Growing Up Star Wars

The Growing Up Star Wars photo pool on Flickr is stellar.

Stellar.

There are over 500 pictures of pictures of kids and adults alike displaying their most prized Star Wars possessions and moments.

I was chatting about the Star Wars era with a friend last week and realized that Return of the Jedi was my first real experience with Star Wars. I remember it vividly. The dessert rescue scene. Whatever that monster in the sand was scared the life out of me. Secretly, though, I couldn’t wait for someone to get pushed in.

The picture above is one of my favorite in the pool. Darth Vader, an Ewok, and some poor kid who had to go as a clown. Look how sad the kid is. Can’t help but laugh.

January 11th, 2009

A New Year, A New Website

2009“New Year” blog posts typically deal with lists. Lists of the best and worst of the preceeding year. This post will be no different. Observe

2008: The Best

Discovering that my pr0n name is Jake Ponderosa and getting people to actually refer to me accordingly.

2008: The Worst

We have a tie between Mamma Mia! and being rejected for Celebrity Rehab.

I do not really want to focus on 2008 with 2009 currently so shiny. 2009 holds so much promise: a new new deal, a new president, new friends, a new Star Trek movie that actually looks good, and a new motto “Feelin’ fine in oh-nine!”

I figured the new year was a great time to redesign erichurst.com. I kicked around a few approaches before settling on this package. I started rewriting the blog engine with Rails. Then realized that to do this the way I really wanted to I would need a virtual private server which I would have to maintain. Rails is a blast for me, but maintaining a server is not. That’s why this blog continues to be powered by good old fashioned Wordpress.

This turned out to be beneficial since at UCLICK we also decided that we would provide creator sites – to those who want them – powered by WP. This leaves us with the task of skinning the app appropriately and adding plugins and widgets as desired. I decided to experiment with my own site and what you now see is the result of said experiments.

I don’t know what to call the design. I’ve narrowed it down to Asian Cowboy, Parquet Party, Fake Brass, & Booyah Bowler. Your thoughts are certainly welcome. I’ll announce a winner this time in 2010.

Besides blogging and developing more there are a few things I’m looking forward to in the coming year.

First, Jen, my wife, is scheduled to give birth to our first child. We’re hoping for a Panda since they are so rare.

Second, in March I’m going to attend SXSWi for the first time. I’m hoping to make new friends, learn a lot, and make convention lanyards sexy again.

Third, I will be joining the Under 200lbs Club again. I’ve been hitting the gym with a buddy and I’m liking how much spandex agrees with me.

I hope you will join me here often in 2009. I’ll share a little of my world, if you will share a little of yours.

August 10th, 2008

Man dances in 42 countries

I’m an avid reader of a We The Robots, a great comic written by Chris Harding (a fellow Kansas Citian). The strip follows the misadventures of Bob, a robot running the rat race day in and day out.

Chris Harding linked to this video from Matt Harding (no relation) recently. I don’t know what the impetus for making this video was, but it’s fun and stunning. Enjoy.

[vimeo]http://www.vimeo.com/1211060[/vimeo]