Detecting a Mobile Browser on the Server in your Rails app

the following code was extracted from my Mobile Ruby on Rails Web App Demo, which was intended as a very simple Mobile Ruby on Rails Web Application (Web App) which uses Ruby 1.9.2, Ruby on Rails 3.0.7 and jQuery Mobile (specifically the jQuery Mobile 1 Alpha 4.1 maintenance release in May 2011.)

The code does a mobile client detection, server side, in the Application Controller by parsing the HTTP_USER_AGENT, or “User-Agent” HTTP header. This is sometimes called “UA sniffing” or User Agent Sniffing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ApplicationController < ActionController::Base
  protect_from_forgery
 
    before_filter :set_browser_type
 
 def set_browser_type
   @browser_type = detect_browser
 end
 
  private
   
  MOBILE_BROWSERS = ["playbook", "windows phone", "android", "ipod", "iphone", "opera mini", "blackberry", "palm","hiptop","avantgo","plucker", "xiino","blazer","elaine", "windows ce; ppc;", "windows ce; smartphone;","windows ce; iemobile", "up.browser","up.link","mmp","symbian","smartphone", "midp","wap","vodafone","o2","pocket","kindle", "mobile","pda","psp","treo"]

  def detect_browser
    agent = request.headers["HTTP_USER_AGENT"].downcase
 
    MOBILE_BROWSERS.each do |m|
      return "mobile" if agent.match(m)
    end
    return "desktop"
  end
 
 
end

The hard part is the Mobile browser user agent list. Sadly I dont remember where I got the original list and then added in the several more recent agent names, but the nature of such things is that it is always out of date! ZYTRAX has a good list of Mobile Browser ID (User-Agent) Strings.

It is used in a ERB view like this :

1
< %= "You don't Look like a Moblie Client :(" if @browser_type != "mobile"  %>

You could also use similar code to control whether to add or change the javascript and css being used, the size of images to use, or additional page elements on the view. In the controller such code could redirect users to the mobile views, if the non mobile views are very different.

If you needed more detailed parsing of the Agent string then Kevin Elliott's Agent Orange looks really good, and goes beyond just mobile browser detection.

West End Toronto Festivals this Weekend,Sept 2011: Bloor West Ukrainian Festival & Roncesvalles Polish Festival

This is the weekend of dueling festivals in west end Toronto : Ukrainian & Polish Festivals.

One in Bloor West Village and one in Roncesvalles Village, only 3 kilometers, that’s 3 subway stops, apart.

The Bloor West Toronto Ukrainian Festival bills itself as “North America’s Largest Ukrainian Street Festival” and runs from Friday, Sept 15, Saturday Sept 16, and Sunday Sept 17, on Bloor Street between Runnymede and Jane.

The Roncesvalles Polish Festival “North America’s Larget Celebration of Polish Culture” and also runs from Friday, Sept 15, Saturday Sept 16, and Sunday Sept 17 and takes place on the whole of Roncesvalles Avenue, from Queen St. West to Dundas St. West.

Taking transit to both is highly recommend.

Both promise much fun, music, dancing, and food for all (you don’t have to be Ukrainian or Polish).

Of course there is another small festival happing in Toronto : the TIFF or Toronto International Film Festival. Maybe Brad Pitt and Angelina Jolie will pop out to the west end?

2011 Trends in Computing : Extreme Mobile

That Mobile is a trend should be a surprise to no one, but Mobile in 2011 looks a lot different from what it looked like in 2000. It’s going to look even more different in 2015. In 2000 mobile was occasionally connected very expensive Laptops (seeking the rare Wifi connection or a privileged Ethernet port) and a very few unconnected PalmPilots, and BlackBerry’s – if you were very special – for email. Now in 2010, Wifi is common and often open, Laptops are cheap, iPhones are the new norm and iPads are the lusted after device, Amazon’s Kindle E-Reader will let you read for a month without recharging, plus Android’s are a mainstream alternative for smart phones and soon -but not yet – for tablets.

But things have changed beyond the just having new devices.

Your Laptop easily has more power than your desktop did in 2000, or it’s a lot cheaper. The new Smart Devices have the power of a Laptop in 2000, at a lower price. Both of these trends have made computing much more widespread then they have ever been.

Smart Devices (Smart Phones, Pads and Tablets, touch iPods) all have capabilities that even todays Laptops do not (yet) have :

  • they are location aware via GPS or Wifi-location triangulation, and they are orientation aware in that they know which why they are pointing
  • they have back and front facing cameras allowing video or still photo’s
  • they have Touch interfaces
  • they are always connected via Cellular Data with Wifi as a backup.

So it is now almost common to always have with you a decent GPS, Camera, and Video Phone; that you can always check something on a pocket encyclopedia or do an instant price compare; and you can play all a games or music or videos or read books all day long. And that’s without considering Augmented Reality (AR) applications that may also leverage access to information and / or processing power on the internet, that can allow for only perviously imaged applications of image and location awareness- answering questions like: where is a thai restaurant near here; It that poison ivy i just stepped in; am I having a heart attack.

So what change is this having on the all of computing?

The number of devices in the market place is changing the economics of computing. It used to be that hardware / software was done for the Military, Government or Big Business, and Consumer hardware / software was adapted from the obsolete leftovers. That has flip over to its reverse. The huge consumer market drives demand, and the Mil / Gov / Big Biz sectors of the economy adapt from the consumer marketplace or struggle to keep up with the speed of inovation. Near Field Communication (NFC) is one example of this that is about to land on the doorstep with a big thump.

Amongst the things that have changed is that the Application Store model (or App Store to use the generic slang) is changing now people find and buy their software, on all their computer planetforms. The Discoverability in the App Store is still weak, but is an vast improvement for non expert users. I expect to see the App Store model to be used soon to deploy and provision applications inside the corporation environment.

There is now also strong need to design for all of those multiple display sizes. Just when we got a handle on working with laptop and desktop monitors with sizes from 15″ to 24″, we now have to consider: Handhelds 3″ to 4″; Tablets 5″ to 7″; Pads or Slates 9″ to 11″; plus – very soon – Wall Units (what used to be called TV’s) 30″ to 70″. HTML5 + CSS3 + Javascript is the best way to fill these needs, but native apps have a place as well.

There is still lots of room at the bottom. “Feature phones” aka “Dumb phones” aka “phone that you use to make phone calls on” are still the vast majority of the market place, especially outside the “West”. The next billion devices will be used in China and India, Nigeria and Brazil. But costs for the device will have to go down dramatically to reach people not in the upper and upper middle class (in the “West” as well). iPods and Android devices are going to address this market. I’m waiting for a Android version of a touch iPod, or a Android with a voice connect and wifi only for Data, or a iPod device with Cellular Data with no voice. The One Laptop per Child (OLPC) project is also a great model for the next 1 billion of computing devices, as is ChromeBooks.  Another kind of “room at the bottom” might be single purpose devices that work with WiFi or BlueTooth that work with a smart enough phone.

Also, having a fast secure connection, means there is less need for large local storage, since you can store in the cloud and cache locally. This will happen with processing as well.

Mobile is now the default. It’s the tail that wags the Dog. Everyone will soon have some kind of connected computing device with them, always. Everything will be Mobile or Cloud (or explain why you are a special case). The expectation is to be able to access information on demand, anywhere, on any device, anytime, in a secure manner. All organizations need to rethink how they can be mobile with their customers and with their employees if they are going to be relevant over the next 10 years.

Rails Migration Rollback with compound indexes fail and fix

Tokyo Train This is for Ruby on Rails 2.5.x, and MySQL 5, and the MySQL2 gem (there is a problem with mysql2-0.3.2. and rails 3.0.x, but using 0.2.7 for Ruby 2.5.x and 3.0.x is good). I do hope to test some of this with other versions of Rails and gems and DB’s. (I expect the problem is in guts of ActiveRecord)

Ruby on Rails best practices calls for adding indexes to your databases, and of course the place to do that is in your migrations (see Always add DB index). Why? Performance!

A related SQL Ninja trick is to create indexes based on fields you filter on (where clauses), or sort on (order by, group by) in your code, not just on the fields you join on (with is what the above link is referring to with reject to foreign keys). The next next level is compound indexes! Compound indexes are called composite keys in some database systems.

If you’re new to this stuff look at A grand piano for your violin on the Giant Robots Smashing Into Other Giant Robots blog, and also Mysql Performance analysis Improve performance by removing unused indexes from the database (on John McCaffrey blog) before you index all the columns – which is almost as bad as no indexes!

The basic syntax for adding a compound composite key index is at it most simplest (you can also require that the compound is unique, or has a certain name) looks like this

1
add_index :accounts, [:branch_id, :party_id]

The issue comes in when you do a rollback and then rake db:migrate, the migrate complains that a index with that name already exists!

1
Mysql2::Error: Duplicate key name 'index_accounts_on_branch_id_and_party_id':

Bummer :(

For regular – single column – indexes, when you drop the column, it’s dropping the indexes for that single column and up don’t have to do anything more that drop that column in the normal Rails migration automagical way:

1
2
3
def self.down
remove_column :accounts, :branch_id
end

but for these fancy dancy compound composite key index thingyes you need to explicitly remove the indexes

1
2
3
4
def self.down
remove_index :accounts, [:branch_id, :party_id]
remove_column :accounts, :branch_id
end

So the lessons from this are:

  1. index
  2. explicitly remove those indexes
  3. test your migrations and rollback, before you need them

that way when you have to do a rollback or do a “rake db:migrate:redo” you’ll won’t lose any (more) hair/sleep over this :)

Twendr – Now in 70 more Locations

on Monday April 11 Twitter rolled out 70 more locations to the previous 42 location (the “World”, 20 Counties and 21 Cities) .

Thankfully I had planed for this and it was trivial to to import and support the new locations. But still, OMG!! We now have 111 locations : the “World”, 31 Counties and 79 cities .

The United States now has 48 cities. Only 12 counties do not have any cities. The UK has 4 cites; Canada has 3 (Montreal and Vancouver join Toronto, so we can see Stanley Cup buzz : ) Japan (and Tokyo) are new, as are United Arab Emirates (UAE), Nigeria and South Africa.

poor hamster :)

this post has been crossposted from the Twendr blog : http://twendr.wordpress.com/2011/04/20/twendr-now-in-70-more-locations/

Also of note : French Web Site “Around The Rézo” or Autour du Rezo has a nice write up on TwendR (post 70 plus) TwendR : un outil en ligne pour connaître les tweets qui enflamment chaque pays. Details and links on the Twendr Blog Twendr : Around The Rézo

April 28th Update : Mashable’s story Social Media Reacts to Marrakesh Bombing links to Twendr!

As we’ve seen during other major events and disasters, people turn to social media channels to share information, prayers and images. And today people have again turned to Twitter, YouTube and other social sites to share news out of Morocco. Marrakesh (or Marrakech) is a trending Twitter topic in Spain, France and the Netherlands, according to Twendr.

Awesome traffic results! I wish it had been a happier event.

Stop SOPA