Thursday, June 25, 2009

Twitter Background Image

I've been using the twitter API and in chirps, I'd like to show user's background from twitter. The twitter api doesn't give this information. If the user chooses to hide the background image by selecting the "Don't use a background image" from the design settings, nothing is passed back through the Twitter API (yet - the fix is in the Twitter API V2 roadmap).

To get around this - I made a method for the User model that returns a boolean for "profile_background_image_display".

def profile_background_image_display
return is_theme? || has_custom_background?

def is_theme?
colors = %w(9AE4E8 C6E2EE EDECE9 0099B9 352726 709397 EBEBEB 8B542B 1A1B1F 642D8B FF6699 BADFCD)
images = (1..12).map{|i| "theme#{i}/bg.gif"}
for i in 0..11
if self.profile_background_image_url =~ && self.profile_background_color.downcase ==
return true
if self.profile_background_image_url =~ /images\/bg.gif/ && self.profile_background_color == # This is the default, not theme 1
return true
return false

def has_custom_background?
return !(self.profile_background_image_url =~ /theme\d+\/bg.gif/)

Note - this isn't perfect. This is where it breaks down:
  • It will show a background image if the user sets a custom background image and hides it.
  • It will show the background image if the user picks a theme and hides the background.
  • It will hide the background image if the user uses a theme background on a custom color.
But those situations are rare, or usually look pretty good anyway. The main problem case - where the user picks a new background color and hides the bg image - is handled here.

That's the trade off.

Hope this is useful to someone - I'd love to know if you have a better solution.

Thursday, June 04, 2009

Case Sensitive Active Record Finds in Ruby on Rails

This was hard to find, so I thought I'd put up a little post.

I was making a site, similar to, where the identifying id in the url string was a sequence of characters (like /jYi1K8c) some lowercase, some uppercase.

With MySQL, you can't just do a Item.find_by_pid('jYi1K8c') and get back the right thing, it will get back the first that matches a case-insensitive search. That is, /ab1, /AB1 and /Ab1 all match the same item.

So, to get around this, there are ways you can set up the migration to indicate the field is case sensitive.

execute %{ALTER TABLE TABLE_NAME MODIFY slug varchar(255) COLLATE utf8_bin NOT NULL}

Apparenty, you can put this right in the migration, and not use 'execute'.

But, I didn't do these. Maybe I will later, but in the short term, I just modified the find conditions in the controller to be like this:

@item = Item.first(:conditions => ['BINARY pid = ?', params[:pid]])

This is a little odd to me - usually rails makes this sort of thing easier to get at. I wouldn't be surprised if there was a better way.