Archive for the ‘Good idea’ 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.

Electra bikes are more than just great bikes

Friday, May 23rd, 2008

Electra Townie 21 in black satinI should first begin with a brief apology. A few weeks ago I posted my thoughts on the KCATA.org website. They weren’t the kindest, and I should have put myself in that designers shoes first. It’s tough designing and developing websites for large organizations; a lot of hands get in the pot and stir things up. I am sure that team did the best they could, and I shouldn’t have criticized the site. That being said, from here on out I shant criticize sites anymore. Flaws are often obvious and don’t need pointing out. If I don’t have something nice to write, I’ll keep it to myself.

Which brings me to the subject of this post: Electra Bikes. Holy moley are these bikes smooth and a complete joy to ride. As this posts headline states, though, it’s more than fantastic bikes that makes Electra great. They are an innovative company that seeks to restore the joy you had riding a bike as a kid.

I started riding my bike to work about three weeks ago. I don’t get to ride every week, but I ride most days. It’s a comfortable four miles each way, although mostly uphill from my office to my home. Before I got the bike in the picture I was riding a Trek 4500 – a great bike for riding trails and such. However, I wanted something more suited for commuting. Enter Jarrod Jarod McBride (twitter.com/concertman), he introduced me to Electra bikes (electrabike.com). The sleek design had me hooked immediately.

It wasn’t long on the site that I was looking for places in Kansas City that sold these bikes. I found a place near me and made my way there (Midwest Cyclery, on Broadway). Fortunately they had one in stock for me to test ride. I knew pretty quickly this was the bike I was looking for and it was in my price range. I still had some questions, though, and decided to ask them directly to Electra if I could.

This is also part of what makes them great, in my humble opinion: on Electra’s website, under the Contact heading you will not find a standard contact form. Instead you will find the names and actual email addresses of the people you may ask questions of. I emailed Elayne, in Marketing, because why not, right? Elayne replied to me within an hour and a half. Perfect. I was even more convinced this would be a company that would stand behind their bikes and offer exceptional service.

Naturally, the lack of contact form got me thinking about web usability. If you are a small business what does it hurt to put a name and email address on your contact page rather than a contact form? Chances are the contact form is just going to go straight to the person you would have the form direct to.

I can see if you need to get technical information from the user, such as browser and OS info, but if you are product oriented, or service oriented, small business like Electra adding a name and email address is a subtle way to build trust with your users and potential customers.

Anyway, I put my scooter up for sale on Craigslist since I had not been riding it and wouldn’t take the time to maintain it properly. Within a few days it sold and I ordered my Townie 21 original in black satin. I also ordered fenders for the tires and the rack on the back. Midwest assembled everything for me and called me yesterday to let me know it was all ready.

If you are looking for a new commuter bike I highly recommend Electra. Spend some time on their site. You will find it informative and full of pictures of their various bikes. Also, if you decide you want one, and you are in the KC area, talk to the guys at Midwest Cyclery, they are cool guys, one dude has a wicked moustache, and they will make sure you are happy with your bike before and after your first ride.

Little Major League experience…

Wednesday, April 9th, 2008

You may be familiar with an improv/performance art group called Improv Everywhere. They pull off some pretty sweet stunts seemingly at random and in public places. My personal favorite is when 50 or so of them all froze in place on cue in Grand Central Station. They held their place for what seemed to be an eternity, then all at once they unfroze and moved on with their actions. People in Grand Central applauded.

The most recent feat I’ve come across from them is this gem. They really put a lot of effort and planning in to one of their productions. They take the time to learn the names and history of people unwittingly involved, and in this case, really deliver an experience only dreamed of. If I were one of the kids in this video I’d be talking about it for years to come.

[youtube]http://www.youtube.com/watch?v=_Nbkbss7i5s[/youtube]

never forget me i am nirodh…

Tuesday, October 30th, 2007

what you are about to view is … well … it’s just … hmmm …

[youtube]http://www.youtube.com/watch?v=BTLj_3R0-2g[/youtube]

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).

my so called music career…

Tuesday, July 31st, 2007

itunes.pngdon’t call it a comeback. i’ve received a few email as of late (like within the last month) from people asking where they could get my triple concrete selling records.

truth is, i stopped touring because it was such a drag. when i stopped touring, people stopped buying records. for a while i kept the records on the site for sale, but they were purchased so infrequently that when i got an order, i’d forget or think it was a joke. that just made people mad, and made me look like a jerk.

i’ve been kicking around the idea of putting at least one of my records up on iTunes and the aforementioned email were just the ticket. starting today you can purchase goodbye, welcome, thankyou, the last record i recorded, on iTunes.

you might see the button in the top right hand corner of the sidebar. just click that link and it will take you straight to my record on iTunes. what’s more, if you buy it, i get a little extra taste cause you clicked through from my site ; )

if’n you don’t want to drag your mouse that far you can click here.

if nothing else, check it out. the record could use a review or two thousand. jen and i just bought a house, so i need the cash!

actually, i’m hoping this goes well enough to warrant putting ben franklin must be proud, my other full length, and the footprint ep on iTunes. we shall see.

finally, don’t hold me to it, but i’ve been writing again. not a lot, but enough. and i’m getting the bug to record. if i do, you’ll be able to get those recordings on my iTunes page.

enjoy.

Teaser…

Wednesday, May 2nd, 2007

I haven’t written much lately, but that doesn’t mean there isn’t a lot on my mind. Following posts will include thus:

  • I know for a fact this blog has at least one more reader: Samuel. I work with this guy, and he’s an all around great person. Me & him are on the fast track to world domination.
  • There is one specific record that is burning a hole in my brain and ears. I can’t wait to share lyrics and music snippets with you dear reader.
  • Steve got shafted at the Doves.
  • I finally get to go to a live production of A Prairie Home Companion!
  • Barack Obama is making a visit to KC on May 12. I may or may not get to go.

So, there you go. Stick close. I promise to write full entries as soon as I can.

In the mean time, feel free to check my Twitter ticker to the right. I update that sometimes several times a day.

One last thing: the Contact page has gone bye-bye until I can find something new that doesn’t send me so much spam. Suggestions?

Why… it’s a major award!

Sunday, February 25th, 2007

steve.jpgSteve Wilson is one of my dearest friends in the world. We came up through college together.

After college Steve married Sarah and they moved to Nashvegas so that he could pursue his dream of being a record producer. To make ends meet he cleaned water coolers, picked up trash and various other manual labor type jobs before finally getting hooked up with some of the right folks.

He now produces records full time and I’m very proud of him. Today, though, I couldn’t be more proud of him as I learned that he’s been nominated for a Dove Award!

Dove Awards are given out to those in the Christian music industry who have demonstrated a level of excellence that is well above average in the past year. He was nominated for his part in writing the song “Sound of Melodies” (iTunes link) as performed by the group Leeland in the category of Rock/Contemporary Recorded Song of the Year (run on sentence?). He says it’s a little thing, but in truth it is a great honor and he should hold his head high (but stay a little humble, bro!).

Congrats man! You deserve this more than anyone I know. I’m more proud of you than you’ll ever know.

Wilkes-Barre(s) PeeCs!

Saturday, February 24th, 2007

wilkesmac.jpgAll I can say is that it is about time higher education started living up to their designated name.  Came across this from a blogger on TUAW.

A university in Wilkes-Barre, PA will remove every PC on campus over the next three years and replace them with the PCs superior counterpart, the Macintosh.  All in all, Wilkes University will replace 1700 computers.  Think Different.

When I was in college there were maybe six Macs on campus.  They were excellent, but neglected by the IT department because frankly they didn’t need any attention.

Kudos to Wilkes University.  I know where my kids will be going!