Archive for the ‘Geek’ Category

Extend has_many with the :extend option

Wednesday, December 9th, 2009

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?

Simple Two Way Encryption for Ruby on Rails

Saturday, November 14th, 2009

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.

Make .bashrc Work for You with Aliases

Sunday, June 7th, 2009

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.

A Developers Responsibility

Friday, June 5th, 2009

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.

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

Thursday, February 5th, 2009

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.

(more…)

Words escape me…

Thursday, April 17th, 2008

This, apparently, is a honest-to-goodness internal Microsoft video meant to inspire the Vista sales force. If this is real, and you still buy Vista after this, you are mom jeans. [youtube]http://www.youtube.com/watch?v=sPv8PPl7ANU[/youtube]

Funny instant message typo’s

Thursday, April 10th, 2008

If you are like me, and you’re not face it, you spend a lot of time in front of your computer with your Instant Messenger client of choice distracting you on a regular basis. Often in my haste to please an IM buddy I’ll quickly type something and I’ve noticed that I make some funny typo’s. So, I’ve amassed them in a brief list. Feel free to add more in the comments section.

  • fort = for - this is typically the result of a fat finger
  • ti’s = it’s - not an ode to Frank McCourt
  • dong = doing
  • abou tit = about it
  • noi = no i
  • meat = me at
  • pees = peace
  • lame = my wife’s cat

Incidentally, any 10.5 users using Spaces frustrated by iChat’s hostile take over of your machine upon a new chat? Do. Not. Want!

amazon mp3

Tuesday, September 25th, 2007

amznmp3_logo.jpgamazon.com announced their new music download site today, and it is pretty dang good. in fact, it’s good enough to win out over iTunes for me.

‘almost internet famous’ blogger, scott mcnulty, posted a pretty well balanced review of amazonmp3 as well as a contrast/comparison of both services on TUAW. scott’s conclusion puts it perfectly, so skip ahead if you want the nutshell.

either way, iTunes finally has a legit competitor.plus, amazonmp3 carries the last Telecas record (which iTunes don’t… and, i loves me some Telecast).

scratching the Surface…

Wednesday, May 30th, 2007

surface03-1.jpg

Well played, FakeSteve. Well played, indeed!

Happy St. Patty’s Day…beware!

Friday, March 16th, 2007

[youtube]7AFYLMNvX1M[/youtube]
I have so much to write about right now, but there just isn’t enough time. Real quick here’s a rundown: Steve the cat has competition for fiercest predator in the hood, Jayhawks gonna run the table, new job update, some movie thoughts, and a goofy photo shoot that I was asked to be a part of. I’ll have to get to all of those over the next week or so.

Right now, though, it is the eve of St. Patty’s day! My buddy Carson Swisher is partly responsible for this wicked funny video involving a drunk leprechaun. Funnier thing is that he and his friend held auditions for the production in his house, and from the looks of it filmed it in his house that he had closed on three days earlier. You can see Carson in the back at one point with a cam in front of his face trying to get out of the way.

I checked on YouTube, the video is up to nearly 5,000 views and the reviews are pretty great. Have fun with the video, made me laugh.

OH! And if you need video production work for anything, you gotta go with Carson. Dude’s p.i.m.p. When you talk to him ask to see his Urban Wakeboarding and Urban Snowboarding videos.

Words I had to look up in this post: Leprechaun, predator and Your Mom.