Home » Archive by category "Code"

Twendr and Twitter Trends – Now in 41 more Locations for 152 places

Twitter has just rolled out (very quietly this month) new trend locations for a total of 152, up from the previous 111. That’s the “World”, 34 Countries and 117 Cities! This is all up on the Twendr Global Trend Dashboard, a big change from a year and a half ago and 11 locations!

There are 3 new countries are Pakistan, Guatemala and Russia ( with the cities of Saint Petersburg, Moscow, and Novosibirsk)

In Japan, Tokyo has been joined by Takamatsu, Okinawa, Fukuoka, Sendai, Kyoto, Sapporo, Nagoya, Osaka, for a total of 9 cities.

and India went from just Mumbai to include 5 more cities: Delhi, Bangalore, Hyderabad, Ahmedabad, Chennai

Brazil went from 2 to 4 cities : Manaus, Brasília, Fortaleza, Salvador

and Indonesia went from 2 to 4 cities with Bandung and Jakarta joined by Surabaya and Bekasi

France now has 3 cities : Lyon, Marseille, Paris

as does Germany : Munich, Hamburg, Berlin

and Netherlands in : Rotterdam, Den Haag, Amsterdam

in Venezuela we have the cities of Barquisimeto, Maracaibo, Valencia joining Caracas

Spain includes Barcelona and Madrid

the Philippines now has Manila and Quezon City

for Turkey we have the 3 cities of Istanbul, Ankara, and Izmir

Sweden now has Stockholm

Mexico now has Monterrey joining Mexico City

in Malaysia we have Kuala Lumpur and Klang

in Nigeria we have Lagos

Ireland has Dublin

and in South Africa we have Johannesburg

You can see all the glory on Twendr.com.

This is a cross post from the Twendr Blog

Doing Conditional Comments for your Internet Explorer css fixes better, with HTML top tag classes

Now browser sniffing is basically a bad thing but there is still a need to fix / hack issues on older browsers, in particular Internet Explorer. Okay, almost entirely in Internet Explorer. IE6 may be -mostly- dead, but IE8 will be around for a long time given that there is no IE9 for WinXP.

The “traditional way” to correct IE issues is using a conditional css style sheet (in the head section ) to load an additional style sheet after the default styles specific to that browser version and take advantage of the cascading part of Cascading Style Sheets (CSS) like so:

1
<!--[if lt IE 8]>       <link rel="stylesheet" href="/css/ie.css" media="screen" />< ![endif]-->

The conditional comments tag is a proprietary IE tag, introduced in IE5, and only works in IE, and “are thus excellently suited to give special instructions meant only for IE”. (IE10 will not support this tag, because it will render perfect HTML5. No ,really.)

I have become aware of a slightly different way to do this via the new hotness of doing feature sniffing ( or Object Detection ) via Modernizer. Modernizer’s trick of loading (or over loading :) ) classes on the tag can be used not only be used for its JavaScript-driven feature detection for html5, but also for creating a top-level class that apply styling to that an individual page or type of page. For a more general description see Why use Classes or IDs on the HTML element?

So technique of “Classes on the HTML tag” was demonstrated by Paul Irish’s back in 2008 (lots of good updates and info there) and a a variation of it is used in Html5 Boilerplate :

1
2
3
4
5
6
<!--[if lt IE 7 ]> <html class="ie6"> < ![endif]-->
<!--[if IE 7 ]>    </html><html class="ie7"> < ![endif]-->
<!--[if IE 8 ]>    </html><html class="ie8"> < ![endif]-->
<!--[if IE 9 ]>    </html><html class="ie9"> < ![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <!--<![endif]-->
</html>

This will allow you to make your corrections close to the original place in your css (or sass) files, general reduce the number of files to maintain and load, and as a bonus it appears to fix problems where the IE conditionals around css files for IE6 can slow down your page load time in IE8!

Note that when this technique was first used, the classes were added on the body tag not the html tag, but best practice suggests the body tag for more dynamic classes (after the page is loaded), although (for example) WordPress does use classes specific to the page being loaded on the body tag.

Extra bonus : If you are using HAML and Rails/Padrino, then Toronto’s Gianni Chiappetta (aka gf3) created a Conditional HTML tag with HAM helper which can also be found in his github repo:

1
2
3
4
5
6
7
8
9
10
def conditional_html( lang = "en", &amp;block )
haml_concat Haml::Util::html_safe &lt; <!--[if lt IE 7 ]>              <html lang="#{lang}" class="no-js ie6"> < ![endif]-->
<!--[if IE 7 ]>                 </html><html lang="#{lang}" class="no-js ie7"> < ![endif]-->
<!--[if IE 8 ]>                 </html><html lang="#{lang}" class="no-js ie8"> < ![endif]-->
<!--[if IE 9 ]>                 </html><html lang="#{lang}" class="no-js ie9"> < ![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--> <!--<![endif]-->
HTML
haml_concat capture( &amp;block ) &lt; &lt; Haml::Util::html_safe( "\n" ) if block_given?
end
</html>

used thusly:

1
2
3
4
5
6
7
!!! 5

- conditional_html 'en-CA'
%head
  %title Website
%body
  = yield

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.

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

James Signs, built as a custom Ruby on Rails CMS site

James Sign home page

Newly launched is the web site of Toronto based http://www.James-Signs.com, a designer and manufacturer of signs and graphics for a variety of applications for both standard stock-type signage and accessories but also catering to the individual needs of a diverse range of entrepreneurs, government, industrial, commercial, and institutional agencies.

The James Signs web site gives background on its long history, but where it really shines is in demonstrating the large sample of example products in it “What we do” section.

James Signs What we Do

The business challenge is to describe the array of products that come under the heading of “Signs”. Outdoor that includes Store fronts and advertising the Business Name, address and services, to assist in parking, or to highlight a sale, in a variety of mediums and manners like banners, swinging signs, raised letter or applied onto the exterior window. Indoor uses include in reception areas, directional, safety and plaques. And signage is used on business and recreational vehicles. A series of galleries is used to give the customer the range of possibilities. (over 190 images at this time). To see further details, the image can be opened in a lightbox

All the content for the site is maintained by the staff of James Signs: navigation, text, and images etc.

James Signs Adminisrative DashBoard

The major navigation is defined by the pages, where the text and images (from media) for those pages is authored (with word processing support via TinyMCE):

James Signs Admin Pages

and the heart of the system is the “product gallery” where “what we do” is defined using sections and sub sections, text and uploaded images (with auto-magical generated thumbnail images with PaperClip and Rmagick):

James Signs Admin Prodcut Gallery

The technologies this site is based on is Ruby on Rails (plus TinyMCE, AuthLogic, paperclip and Rmagick) , jQuery (plus JQuery ui accordion sections, and the Slimbox Lightbox plugin), CSS3, and MySQL used to create a custom Content Management Sites (CMS) that address what James Signs needed.