Wednesday, December 31, 2008

Woopra.com

What is Woopra?

Woopra is the world's most comprehensive, information rich, easy to use, real-time Web tracking and analysis application. And it's free! Learn more...

Woopra’s revolutionary server architecture, combined with its intuitively designed client software, enables seamless tracking of visitors. Webmasters can track over 40 different statistical events and analytics. Never before has so much information been instantaneously available to Webmasters. Most analytical and site statistics are updated once a day at the least, or several times during the day. With Woopra, you get live track of visitors coming and going and moving through your site. You get the stats now.

http://www.woopra.com

Monday, December 29, 2008

How to reduce the memory usage on Firefox?

How to reduce the memory usage on Firefox? This article gives you simple steps to optimize your PC memory usage

Most of the time, Firefox doesn't use abnormal amount of system memory, however it does sometimes due to other sources, like number of plug-ins, themes and extensions. It is also highly recommended that you have the latest version of Firefox as the memory usage is minimized. If you want to download the latest copy of Firefox, click here.

Follow these steps to check what is causing the abnormal memory usage:
  • Clear Download History.
  • Restart Firefox Periodically.
  • Assign Memory Cache on Firefox.
  • Release Memory when Firefox is minimized
Clear Download History:

Keeping the Download History can cause extensive usage of memory and this can slow down or freeze Firefox.

  1. Delete the "downloads.rdf" file to clear the download history.
  2. You need to make a little change to the browser setting. Here's what you do:
  3. Open Firefox browser.
  4. From the menu bar, click Tools -> Options.

  5. Click Privacy. Un-check the "Remember What I've downloaded" check box.


Restart Firefox Periodically:

There might be a constant increase in the memory usage if you are using Firefox for a long period of time or handling multiple sessions.
  1. Consider restarting your browser periodically so that it can maintain a constant memory usage.
  2. Download and Install Session Manager Extension, which would save the current text data, history and cookies. It allows you to maintain the opened web pages when Firefox is closed.

Assign Memory Cache on Firefox:

Firefox doesn't use memory cache and uses system memory by default, it is good to assign a fixed memory cache to reduce the usage of memory. Here's how you do it:

  1. Open the Firefox browser.
  2. Key in about:config in the address bar.

  3. Key in browser.cache.memory.enable in the Filter field.

  4. Ensure the value of the above item is set it true, if not, double-click on it to set it to true.
  5. Right-click in the browser and select New -> Integer from the pop-up.

  6. Key in, browser.cache.memory.capacity, click OK.

  7. You need to enter a value here and that value depends upon the RAM your computer has.

  8. if you have:
    1. 256MB RAM - Enter "4096".
    2. 512MB RAM - Enter "8192".
  9. Note: If you have 128MB or less RAM then you need to upgrade your RAM. It is not very expensive.
Important: If you want to restore to default settings then change browser.cache.memory.capacity value to -1 (minus 1).

Release Memory when Firefox is minimized
  1. Open the Firefox browser.
  2. Key about:config in the address bar.


  3. Right-click in the browser and select New -> Boolean from the pop-up.


  4. In the popup box enter config.trim_on_minimize. Click OK.


  5. Select True and then click OK.


  6. Restart Firefox.

Thursday, December 25, 2008

MySQL Command Tips

pager less -niSFX (pager format to long data table)

mysql sends each SQL statement that you issue to the server to be executed. There is also a set of commands that mysql itself interprets. For a list of these commands, type help or \h at the mysql> prompt:
mysql> help

List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
? (\?) Synonym for `help'.
clear (\c) Clear command.
connect (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter. NOTE: Takes the rest of the line as
new delimiter.
edit (\e) Edit command with $EDITOR.
ego (\G) Send command to mysql server, display result vertically.
exit (\q) Exit mysql. Same as quit.
go (\g) Send command to mysql server.
help (\h) Display this help.
nopager (\n) Disable pager, print to stdout.
notee (\t) Don't write into outfile.
pager (\P) Set PAGER [to_pager]. Print the query results via PAGER.
print (\p) Print current command.
prompt (\R) Change your mysql prompt.
quit (\q) Quit mysql.
rehash (\#) Rebuild completion hash.
source (\.) Execute an SQL script file. Takes a file name as an argument.
status (\s) Get status information from the server.
system (\!) Execute a system shell command.
tee (\T) Set outfile [to_outfile]. Append everything into given
outfile.
use (\u) Use another database. Takes database name as argument.
charset (\C) Switch to another charset. Might be needed for processing
binlog with multi-byte charsets.
warnings (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.

For server side help, type 'help contents'
Each command has both a long and short form. The long form is not case sensitive; the short form is. The long form can be followed by an optional semicolon terminator, but the short form should not.

http://dev.mysql.com/doc/refman/5.0/en/mysql-commands.html

Wednesday, December 24, 2008

Merb gets merged into Rails 3!

It’s christmas, baby, and do we have a present for you. We’re ending the bickering between Merb and Rails with a this bombshell: Merb is being merged into Rails 3!

We all realized that working together for a common good would be much more productive than duplicating things on each side of the fence. Merb and Rails already share so much in terms of design and sensibility that joining forces seemed like the obvious way to go. All we needed was to sit down for a chat and hash it out, so we did just that.

What this will mean in practice is that the Merb team is putting their efforts into bringing all of the key Merb ideas into Rails 3. Yehuda Katz will outright join the Rails core team, Matt Aimonetti will work on a new evangelism team, and Carl Lerche and Daniel Neighman (hassox) will be co-starring the effort to bring all this over. We’ve immortalized the merge with plaque page at rubyonrails.org/merb.

http://weblog.rubyonrails.org/2008/12/23/merb-gets-merged-into-rails-3

Monday, December 22, 2008

FireBug Console API

Firebug adds a global variable named "console" to all web pages loaded in Firefox. This object contains many methods that allow you to write to the Firebug console to expose information that is flowing through your scripts.

http://getfirebug.com/console.html

On Your Best Behavior: Prototype, LowPro, and Responsible Scripting

The Prototype JavaScript library was born out of the aura that was the early days of Ruby on Rails, and it has grown into a respectable framework used on many high profile sites. ProtoType is a general purpose framework, adding convenience methods to many of JavaScript’s built in object types. This approach makes it easier to write more concise, explanatory code, but it has also generated legions of Prototype dissenters. I think it’s safe to say Prototype is the right library for some developers and situations, and other libraries may be a better fit for others. Plenty of sites are built with Prototype, and plenty more will be; my goal here is to show how to use Prototype the right way.

If you’re working on a jQuery-based project, there’s a version of LowPro for you too. The rest of this article will be solid theory, but the syntax used in the following examples uses Prototype.

Problems with Prototype

The biggest problem that I’ve personally had with Prototype is it tends to be slow to adopt best practices emerging in other libraries. For example, it had an anemic event model before version 1.5, and it didn’t natively support any kind of DOM-ready event until 1.6. Luckily, there has been another small JavaScript library that has filled in these functionality gaps for quite some time- LowPro. It you are using Prototype to write your client side code, you should install LowPro before you install Script.aculo.us. If you’re using Rails, add installing LowPro to your list of new project setup tasks.

In my opinion, LowPro should have been merged into Prototype long ago. And while its code has never made it into Prototype’s codebase, over time, LowPro’s intentions have been gradually assimilated. As a result, LowPro’s role has grown smaller with each release of Prototype, and today it serves one primary purpose: binding behaviors to page elements. It also has some convenience methods for constructing DOM elements, but I won’t be dealing with those in this article.

An introduction to twenty-first century scripting

It’s 2008. There is a short list of things that should never be seen in markup from this point forward:

  • inline event handlers
  • script elements outside of your document’s head

Yes, this includes your Google Analytics tracking scripts. Put those script tags in your document’s head where they belong, and use DOM ready events to fire your tracking.

The key to modern scripting is in your markup. Make it as semantic as you can. Use class names that makes sense, more than one if necessary. Use microformats if you can. Once you do this, you will find id attributes become much less important. I tend to only use them for database objects these days- and even then it can get you into trouble.

There are a lot of third party libraries that expect to be passed an element with an id attribute to function properly. I believe parts of Script.aculo.us are like this. Do not allow these libraries seduce you into adding id attributes where you do not otherwise need them. Behavior-based JavaScript is based around the relationship between elements in the DOM. In most cases, none of the elements need id attributes. From inside behaviors, use DOM traversal methods to find other nodes you need to work with.

With that covered, let’s move on to some code examples.

LowPro Basics

The core of LowPro revolves around two functions: Event.addBehavior and Behavior.create. Event.addBehavior can map DOM elements to anonymous functions based on CSS selectors:

Event.addBehavior({
'div.main': function() {
// 'this' is a reference to a matching DOM node
},
'div.secondary,div.tertiary': function() {
// multiple CSS selectors can be separated by a comma
}
});

Event.addBehavior also supports attaching event listeners to DOM elements. Note how the CSS selector has a pseudo-class appended to it:

Event.addBehavior({
'div.main:click': function(event) {
// 'this' is a reference to a matching DOM node
// 'event' it the standard Prototype-extended event object
}
});

Now when a user clicks on a page element that matches the selector ‘div.main’, the anonymous function is passed the standard Prototype-extended event object and executed, which is cool. This is a good place to start when writing behaviors, since a good portion of the time, a single event handler will do the job. But if you start to see a lot of duplication of selectors or you need to maintain a state information for your various event handlers to use, it’s best to move to creating Behavior classes.

Oh, Behave!

Here’s what a simple Behavior looks like- it’s generally a good idea to define your behaviors first, and then reference them inside an Event.addBehavior block:

var SimpleBehavior = Behavior.create({
initialize: function() {
// Called when the behavior is created
// 'this' is a reference to the Behavior instance
// 'this.element' is a reference to the matching DOM element
},
onclick: function(event) {
// 'this' and 'this.element' work the same way as in initialize
// All 'on...' methods are automatically bound as event listeners
// to their respective events
},
otherMethod: function(arg) {
// You can add other methods to the behavior object
}
});

Event.addBehavior({
'div.main': SimpleBehavior
});

Behavior.create works a lot like Prototype’s Class.create- both return class objects that support pseudo-inheritance. You can use these classes and the new keyword to instantiate a behavior. Doing so requires the first argument to the constructor be the DOM element to bind the behavior to. This is what Event.addBehavior does behind the scenes.

new SimpleBehavior(element);

Remember that if you want to store data in properties on the Behavior object instance, the correct way to do so is initialize those properties in an initialize function:

var BehaviorWithProperties = Behavior.create({
initialize: function() {
this.property = 'value';
}
});

A common point of confusion is how behaviors and DOM elements interact. LowPro Behavior classes (and the rest of the examples in this article) involve the interaction of two parts: an instance of the Behavior class, and the DOM element this instance is bound to. I find that this is a stumbling point, but it’s simple once the you grasp the way these parts interact: the behavior instance has a reference to the DOM element, but the DOM element knows nothing of the behavior. This is in part to get around some circular-reference memory leaks in certain JavaScript interpreters, and partly because this pattern has emerged as a good design pattern to follow when implementing user interfaces.

Pseudo-inheritance, Prototype style.

Behavior.create handles subclassing behavior in the same way that Prototype’s Class.create does. By writing basic behaviors and then extending them for your application-specific purposes, you can build up a library of general behaviors that solve common problems. I usually try to identify a generic behavior component when I’m writing a new behavior, and finish that before building any application specific code.

var Parent = Behavior.create({
initialize: function() {
this.element.addClassName('crazy');
}
});

var Child = Behavior.create(Parent, {
initialize: function($super) {
$super();
this.element.hide();
}
});

DOM Ready and You

Old-school JavaScript taught developers to use inline onload event handlers on a document’s body element to call page initialization methods. The trouble with this is we don’t really want the page load event, because it is fired once the page is finished loading. For scripting purposes, all we care about is the DOM being fully parsed and assembled. Starting in version 1.6, Prototype has supported custom events, the most vital of which is ‘dom:loaded’. This event is fired right when we need it to: once the DOM is ready.

Event.addBehavior hooks into Prototype’s ‘dom:loaded’ event, and waits until then to look for elements to initialize. Remember that if you instantiate behaviors using JavaScript’s new keyword, you need to make sure to do it after the DOM has been loaded.

var MyBehavior = Behavior.create({
initialize: function() {
this.element.addClassName(Cycle.thru('odd', 'even'));
}
});

document.observe('dom:loaded', function() {
$$('ul.products li').each(function(element) {
new MyBehavior(element);
});
});
Now Go Out and Make The World a Better Place

I’ve found LowPro to be an essential tool for writing user interfaces over the last year. It’s greatest downside has always been its somewhat sparse documentation, which I hope to have somewhat rectified with this article. Be sure to check out Dan Webb’s website for more LowPro and other web goodness. And the LowPro Google Group is a great place to go for help and discussion.

http://autonomousmachine.com/2008/8/24/on-your-best-behavior-prototype-lowpro-and-responsible-scripting

Firebug lite for all those other browsers

If for some reason you use one of those other browsers, then you don’t have the pleasure of using Firebug for debugging (Safari nuts, I know you secretly debug your javascript and stylesheets with Firebug in Firefox, despite it “not looking like a Mac app”).

Fortunately for you, there’s Firebug Lite. From the website:

Firebug is an extension for Firefox, but what happens when you need to test your pages in Internet Explorer, Opera, and Safari? If you are using console.log() to write to Firebug’s console, you’ll wind up with JavaScript errors in these other browsers, and that’s no fun.

The solution is Firebug Lite, a JavaScript file you can insert into your pages to simulate the Firebug console in browsers that are not named “Firefox”.

To ease the pain of debugging Javascript in those other browsers, I’ve thrown together a little plugin that automagically includes Firebug Lite into your application in development mode. All you need to do is install the plugin and include the default javascripts in your layout (which you’re probably already doing):

<%= javascript_include_tag :defaults %>

Just hit F12 (Ctrl+F12 on Mac) to open Firebug Lite on any page, or jump the focus directly to the command line with Ctrl+Shift+L (or ⌘+Shift+L on Mac).

http://source.collectiveidea.com/public/rails/plugins/firebug

Tuesday, December 16, 2008

Saturday, December 13, 2008

How to access session, cookies, params, request in Model

You’re completely/totally/fucking wrong if you want to access sessions, params, cookies, etc. in your Models.

You can’t get more wrong than this in rails world probably. But some people just don’t get it. So if you must, this is how you can do it
Add this code at the bottom of your application.rb

class ApplicationController
# Your existing stuff
around_filter :you_dont_have_bloody_clue

protected

def you_dont_have_bloody_clue
klasses = [ActiveRecord::Base, ActiveRecord::Base.class]
methods = ["session", "cookies", "params", "request"]

methods.each do |shenanigan|
oops = instance_variable_get(:"@_#{shenanigan}")
klasses.each{ |klass| klass.send(:define_method, shenanigan, proc { oops }) }
end

yield

methods.each { |shenanigan| klasses.each{ |klass| klass.send :remove_method, shenanigan } }

end

Again, do it if you wish, just don’t ask anyone how to do it ever again!

http://m.onkey.org/2007/10/17/how-to-access-session-cookies-params-request-in-model

Thursday, December 11, 2008

Button Width in IE

Ever been annoyed with extra padding in a input button in Internet Explorer?

However, as it turns out, that fix doesn't work so well when the button is inside a table cell. Here is an image of the problem (table cell in red) and a workaround for that.

The workaround is to use width:1; by default and feed IE a different value (width:auto;) using a conditional comment. It actually works pretty well.



http://jehiah.cz/archive/button-width-in-ie-revised

Wednesday, December 10, 2008

DD_belatedPNG

  • You can use 24-bit alpha-translucent PNG images for the background-image CSS property in Internet Explorer 6.
  • Support for background-position and background-repeat. Apparently Angus of TwinHelix has also figured out a way!
  • There is no usage of AlphaImageLoader, so this doesn't have the buggy z-indexing associated with that filter.
  • Responds to Javascript element.style assignments and the :hover pseudo-class.
  • ~7.5Kb uncompressed … ~6Kb compressed
  • Easy implementation:
    <!--[if IE 6]>
    <script src="DD_belatedPNG.js"></script>
    <script>
    DD_belatedPNG.fix('.png_bg'); //EXAMPLE
    </script>
    <![endif]-->

http://www.dillerdesign.com/experiment/DD_belatedPNG/

Monday, December 8, 2008

Default Scoping

It’s pretty common to want SQL queries against a particular table to always be sorted the same way, and is one of the reasons why I added the ordered scope to the utility scopes gem. For instance, when dealing with collections of articles it is reasonable to expect that the default ordering be most recent first, i.e. created_at DESC. Well now you can specify default ordering, and other scopes, in edge rails directly in your ActiveRecord model.

Taking our Article example let’s specify the aforementioned default ordering:

class Article < ActiveRecord::Base
default_scope :order => 'created_at DESC'
end

Now, when any find method or named_scope is executed the default ordering comes along for the ride:

Article.find(:all) #=> "SELECT * FROM `articles` ORDER BY created_at DESC"

The same holds true for any named scopes you might have:

class Article < ActiveRecord::Base
default_scope :order => 'created_at DESC'
named_scope :published, :conditions => { :published => true }
end

Article.published #=> "SELECT * FROM `articles` WHERE published = true ORDER BY created_at DESC"

There are some things to keep in mind, however. First is that scopes like :join, :offset, :limit and :order will get clobbered by the innermost rule. For example, here the default scope ordering loses out to the named_scope ordering.

class Article < ActiveRecord::Base
default_scope :order => 'created_at DESC'
named_scope :published, :conditions => { :published => true },
:order => 'published_at DESC'
end

# published_at DESC clobbers default scope
Article.published #=> "SELECT * FROM `articles` WHERE published = true
ORDER BY published_at DESC"

Also keep in mind that the default scoping is inherited, so child-classes of Article will have the same default scoping.

And for those occasions when you want to override or remove your default scope, just use with_exclusive_scope:

class Article < ActiveRecord::Base
default_scope :order => 'created_at DESC'
end

# Ignore other scoping within this block
Article.with_exclusive_scope { find(:all) } #=> "SELECT * FROM `articles`

default_scope is a great way to specify reasonable query defaults and relieve yourself of having to create your own named_scopes for that purpose or specify such conditions at every invocation. Yes, I just said ‘relieve yourself’... giggity giggity

http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping

Object.try

Those of you using Chris Wanstrath’s slick little try trick will now have access to that functionality in Rails with this ActiveSupport update.

Basically, try lets you attempt to invoke a method on an object without worrying about a NoMethodError being raised. If the method doesn’t exist, or if the target object nil, then nil will be returned without exceptions:

# No exceptions when receiver is nil
nil.try(:destroy) #=> nil

# Useful when chaining potential nil items
User.admins.first.try(:address).try(:reset)

Just a small little bit of syntactical candy pulled in from the community.

Update: You can now also use this trick for methods with arguments

http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-object-try

What's New in Edge Rails: :except and :only Routing Options

Just added to Edge Rails is the ability to exclude and include the default generated routes in your mapping configuration. Previously, map.resources :articles would generate routes to all seven default actions on the ArticlesController (index, create, new, edit, show, update, destroy). You can now tell your routes configuration to only generate a subset of those actions, or to exclude a subset of those actions:

# Only generate the :index route of articles
map.resources :articles, :only => :index
# Generate all but the destroy route of articles

map.resources :articles, :except => :destroy
# Only generate the non-modifying routes of articles

map.resources :articles, :only => [:index, :show]

Note that you can use the :all and :none values to denote all or none of the default routes.

# Don't generate any default article routes, just the approve route
map.resources :articles, :except => :all, :member => { :approve => :put }
# Same
map.resources :articles, :only => :none, :member => { :approve => :put }

You should also note that these options will be inherited by nested resources that don’t override them. For instance, in this example, comments would only have the :index and :show routes exposed:

# Because comments are nested within articles, they too will only
# have the index and show routes generated.
map.resources :articles, :only => [:index, :show] do |article|
article.resources :comments
end

Specifying either an :except or :only option in a nested resource will override its parent resource’s options. E.g. this routing will result in comments having all actions but :show routed:

map.resources :articles, :only => [:index, :show] do |article|
# My :except option overrides my parent resources :only
article.resources :comments, :except => :show
end

The motivation behind this feature is that complex routing consumes a lot of memory. So eliminating unnecessary and unused routes can significantly reduce your memory consumption. The holy grail of this, however, will be when you can specify which routes should be formatted (json, xml etc…) as this is essentially doubling the number of default routes when very rarely does every call need to be API-accessible.

http://ryandaigle.com/articles/2008/11/13/what-s-new-in-edge-rails-except-and-only-routing-options

No More Formatted Routes

Parallel to the addition of :except and :only options to Rails’ routing comes the removal of all those formatted_xxx named routes. Turns out these routes ate up a lot of memory and served minimal purpose.

So with this routes.rb definition:
ActionController::Routing::Routes.draw do |map|
map.resources :articles
end

you’ll no longer have any of the formatted_xxx url helpers available. However, you will be able to get the same functionality by passing in a :format option to the base view helper methods:

# Old => New
formatted_article_path(article, :xml) =>
article_path(article,
:format => :xml)
formatted_new_article_path(:json) =>
new_article_path(
:format => :json)
# etc...

A minimal change that will have a big impact on the memory consumption of each of your Rails processes – especially if you’ve got a complex app with lots of routes.

If you’re on Edge Rails you’re going to start seeing deprecation warnings where you reference these formatted url helpers, so you’ve got some warning before you have to make the switch.

http://ryandaigle.com/articles/2008/11/27/what-s-new-in-edge-rails-no-more-formatted-routes

Saturday, December 6, 2008

Implementing super in JavaScript

Erik Arvidsson seems to be having fun going through exersizes getting JavaScript to do something his way. The latest little foray is Using catch-alls to implement super.

Firstly, catch-alls are the ability to use the SpiderMonkey only __noSuchMethod__ meta programming trick. The good news is that this seems to be coming to ECMAScript Harmony (I hope we here how the ECMA working group meeting went in Kona soon!).

Erik used this trick to build a createSuper method:

function createSuper(self, opt_constr) {
var constr = opt_constr || arguments.callee.caller;
function supr() {
return constr.superClass.apply(self, arguments); }
supr.__noSuchMethod__ = function(name, args) {
if (typeof constr.superClass.prototype[name] == 'function') {
return constr.superClass.prototype[name].apply(self, args); }
throw Error('No such method, ' + name);
}
return supr;
}

which you can then use via var supr = createSuper(this);
Of course, as Erik points out, you can just use FooClass.superClass.method.call(this, …);

http://ajaxian.com/archives/super-js

Translate your language with Google::Translate

require 'rubygems'
require 'google_translate'

tr = Google::Translate.new

# from English to German
tr.translate :from => "en", :to => "de", :text => "Hello, World!"

# => "Hallo, Welt!"

# from English to Spanish
tr.translate :from => "en", :to => "es", :text => "Hello, World!"

# => "Hola, mundo!"

Thursday, December 4, 2008

SQL: Ordering with NULL values

Ordering in SQL is quite easy:
SELECT * FROM people ORDER BY nick_name;

This would result in a nice table like this:

id nick_name
3 Ariejan
2 Harm
1 Ralph

Now, let’s say for some reason you have NULL values in the nick_name column. This may be because you allow NULL values here, or because you’re doing a LEFT JOIN or something else crazy. Having NULL values will result in the following:

id nick_name
4 NULL
5 NULL
3 Ariejan
2 Harm
1 Ralph

This is not always desireable. It’s very well possible that you want to sort all non-NULL values first. If you know the following trick, it’s quite easy. (Actually, it’s not a trick, just some creative SQL writing).

SELECT * FROM people ORDER BY nick_name IS NULL, nick_name;
id nick_name
3 Ariejan
2 Harm
1 Ralph
4 NULL
5 NULL

How does this work? The ORDER BY nick_name IS NULL part will create a new (virtual) column that stores the result of nick_name IS NULL. If the field contains a nick_name the resulting value is 0, if there’s a NULL value it will contain 1. Sorting by this virtual attribute will sort 0’s before 1’s. After sorting the NULL’s to the bottom, you may specify other sorting criteria, such as the normal nick_name.

http://blog.kabisa.nl/2008/11/14/sql-ordering-with-null-values/

Export CSV directly from MySQL

How ofter were you asked by a client for a CSV (or excel) file with data from their app? I get asked that question quite often, so I wanted make the process as easy as possible. And guess what? You can create CSV files directly from MySQL with just one query!

Let’s say you want to export the id, name and email fields from your users table to a CSV file. Here is your code:

SELECT id, name, email INTO OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE 1

Well, if you know MySQL, you’ll know how to customize this query to spit out the the right data. Your csv file can be found in /tmp/result.csv

Make sure your MySQL server has write permissions to the location where you want to store your results file.

http://ariejan.net/2008/11/27/export-csv-directly-from-mysql/

CruiseControl.rb

Cruise_logo_largeCruiseControl.rb is a continuous integration tool. Its basic purpose in life is to alert members of a software project when one of them checks something into source control that breaks the build.

CC.rb is easy to install, pleasant to use and simple to hack. It's written in Ruby.

Believe it or not, you have to download CruiseControl.rb in order to use it. Download it now
You can watch us setup a typical rails project, or read more on the getting started page.

http://cruisecontrolrb.thoughtworks.com/

Extend Your ActiveRecord Association Methods

Much of the beauty of ActiveRecord associations is in the collection methods that are provided for you when you define has_many relationships.

For instance, when we say:
class Organization < ActiveRecord::Base
has_many :people
end

We now have an organization.people method that returns the collection of associated people within the organization. Easy enough. We also get nice little methods on the collection of people like organization.people<<, organization.people.build, organization.people.create and organization.people.find (among others). Well what if you wanted to define your own method on this auto-magically provided collection method? You do this through Association Extensions which let you define methods to add to the collection. You can define an association extension either with a block or a module – we’ll use a block provided to the has_many call here as it’s the most common way to do so:

class Organization < ActiveRecord::Base
has_many :people do
def find_active
find(:all, :conditions => ["active = ?", true])
end
end
end

I’ve defined a find_active method which will retrieve all people in the organization that have the active column set to true. This can be invoked very intuitively with:

organization.people.find_active

This is a great way to provide convenience finder methods for common retrievals on the associated collection.

If you want to define an extension as a module just provide the :extend option in your has_many definition:
module FindActiveExtension
def find_active
find(:all, :conditions => ["active = ?", true])
end
end

class Organization < ActiveRecord::Base
has_many :people, :extend => FindActiveExtension
end
You can customize to your heart’s content – these are just some simplistic examples of how to plug into this nifty feature.

Gem Dependencies

Rails plugins are great for many reasons, one being that they provide extra functionality without being an external dependency – they’re packaged right there with your application. Until recently, there was no way do programmatically define a Rails applications’ external gem dependencies and we were left with rolling our own gem dependency solutions.

That all changes with a nice way to define, and tie, gem dependencies to our Rails apps. In our environment.rb we have the following:

Rails::Initializer.run do |config|

# Require the latest version of haml
config.gem "haml"

# Require a specific version of chronic
config.gem "chronic", :version => '0.2.3'

# Require a gem from a non-standard repo
config.gem "hpricot", :source => "http://code.whytheluckystiff.net"

# Require a gem that needs to require a file different than the gem's name
# I.e. if you normally load the gem with require 'aws/s3' instead of
# require 'aws-s3' then you would need to specify the :lib option
config.gem "aws-s3", :lib => "aws/s3"
end
So great – when your app loads up it will automatically find and require each of the gems you’ve listed. But what if you’re on a system that doesn’t have all of these gems installed, or you’ve just deployed to a fresh environment? There’s now a rake task that will install all the referenced config.gems on your target system:

rake gems:install

Before running this you can see what gem dependencies your app has by running rake gems.

However, this still doesn’t package these gem dependencies with the app, it only refers to system-dependent gems. If you want to pull these gems into your application source you can do so with the new rake gems:unpack task:

# Unpack all gems to vendor/gems
rake gems:unpack

You can also unpack individual gems:

# Unpack only the hpricot gem to vendor/gems
rake gems:unpack GEM=hpricot

This will unpack the gem into the vendor/gems/hpricot-0.5 directory which is automatically searched as part of the config.gem startup.

Your deployment strategy can now choose to automatically install required gems in each target environment or just package gems as part of the application source.

Update: Just added is the ability to build gems that have native extensions:

rake gems:build

http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies

Tuesday, December 2, 2008

PHP / Ruby-style Javascript

A lot of people are familiar with PHP's functions, and though Javascript functions are often quite similar, some functions may be missing or addressed differently. The Javascript implementations should be as compliant with the PHP versions as possible, a good indication is that the PHP function manual could also apply to the Javascript version.

Porting crucial PHP functions to Javascript can be fun & useful. Currently some PHP functions have been added, but readers are encouraged to contribute and improve functions by adding comments. Eventually the goal is to save all the functions in one php.js file and make it publicly available for your coding pleasure.

If you choose to contribute, let me know how you want to be credited in the function's comments. You may also want to subscribe to RSS so you receive updates whenever new functions are posted.

http://kevin.vanzonneveld.net/

JS.Class 2.0
JS.Class is a library designed to facilitate object-oriented development in JavaScript. It implements Ruby’s core object, module and class system and some of its metaprogramming facilities, giving you a powerful base to build well-structured OO programs.

http://jsclass.jcoglan.com/
http://www.randomhacks.net/articles/2007/07/01/ruby-metaprogramming-javascript-rspec-bdd

Monday, December 1, 2008

Anatomy of a DOCTYPE

An Explanation of the DOCTYPE Identifier
A typical DOCTYPE you might see on an HTML document is the HTML 4.01 transitional DOCTYPE. The DOCTYPE isn't exactly an HTML tag or XHTML element. Instead it is a declaration and always appears at the very top of your documents.

A DOCTYPE is made up of the following parts:
  • !DOCTYPE
    The identifier. It indicates to the user-agent that the enclosed information will define the type of document of the page.
  • HTML
    The Top Element. This tells the browser what element to expect as the top-level element. For HTML and XHTML documents this element would be <html>
  • PUBLIC
    The Availability. The most common DOCTYPES you will use will be publicly available - "PUBLIC". But you can also specify a local DTD with the "SYSTEM" key word.
  • "-//W3C//DTD HTML 4.01 Transitional//EN"
    The Formal Public Identifier. This entire string is what identifies the DOCTYPE.
The FPI is made up of these parts:
  • -
    Registration. If there is a plus-sign (+) here, that means that the organization is registered with the ISO. A minus-sign (-) indicates that it is not registered.
  • W3C
    The Organization. This is the group that owns and maintains the DOCTYPE being used.
  • DTD
    The Type. This defines the type of DOCTYPE used.
  • HTML 4.01 Transitional
    The Human-Readable Label. This is the label that tells you what DTD is being used. It is written so that humans, rather than computers, can understand it.
  • EN
    The Language. This is the language that the DTD is written in. It is not the language of the content of the page.
The rest of the DOCTYPE identifier is optional:
  • "http://www.w3.org/TR/html4/loose.dtd"
    The URI. This is an optional URL indicating where the DTD for this DOCTYPE can be found.
http://webdesign.about.com/od/dtds/qt/tipdoctype.htm

Thursday, November 27, 2008

Speed.io

Speed.io is a modern DSL speedtest to analyze your broadband internet access. You find that your internet connection is too slow or you are just curious how fast you are - speed.io is a perfect tool for a fast speed check - worldwide.

speed.io measures your current internet speed to the nearest server (we have almost 50.000 server worldwide). We test your download (speed with which you receive data from internet), upload (speed with which you send data to the internet), connection test (maximal number of connections per minute) as well as ping (response time between your computer and the internet).

All test are performed within your browser over HTTP (TCP) and requires no further software than a newer browser with activated Flash.

http://www.speed.io

Sunday, November 23, 2008

Connection Pools

With the upcoming thread-safety of Rails comes the necessity of database connection pools. While less a feature and more a hidden implementation detail, you do have the ability to adjust the max size of these new pools (default is 5). In your database.yml configuration file just set the pool key:
development:
adapter: mysql
username: root
database: myapp_dev
pool: 10

Rails 2.1.2 and 2.2: Update Your RubyGems

There’s a mismatch between the most recent Rails releases (2.1.2 and 2.2RC1) and older versions of RubyGems. Judging by what I’ve seen in various discussion fora, this is well on the way to being a FAQ. It’s made more fun by the facts that

  • The error message doesn’t implicate RubyGems
  • You may think you’re up-to-date on RubyGems when you’re not
  • If you’re affected, you’ll see this message when you try to run script/generate in a Rails application:
    undefined method empty?' for /_generator$/:Regexp

    If you see this, don’t panic. It just means you need a newer RubyGems release. I’m not sure how current you need to be, but 1.1.1 is definitely too old. As I write this, 1.3.0 is current.

    Now, in theory, to update to the latest version of RubyGems, you just need to run
    sudo gem update --system

    But - depending on what version of RubyGems you have installed, running that command may lie and tell you that you have nothing to update. If you’re currently on RubyGems 1.1 or 1.2, you need to run a different set of commands to update RubyGems:
    sudo gem install rubygems-update
    sudo update_rubygems

    You can check your current RubyGems version with
    gem -v

    If it reports 1.3.0 or later, you should be good to use the recent Rails releases.

    Thursday, November 20, 2008

    Adding input:focus functionality to IE using prototype.js

    JS:
    Event.observe(window, 'load', function() {
    var fields = $$("input");
    fields.each(function(el) {
    $(el).observe('focus', function(){this.addClassName('focused');});
    $(el).observe('blur', function(){this.removeClassName('focused');});
    });
    });

    CSS:

    input:focus, /* works in FF without javascript */
    input.focused /* used by js */
    { background-color: #f7cd72; }

    Thursday, November 13, 2008

    WTFramework bookmarklet

    Ever wondered which JavaScript framework was used on a specific website but was too lazy to check the source code for the answer? Fear no more WTFramework is here.

    Here we have the work of my life – where by saying life I mean 20 minutes of it. This is a pretty simple and straight–forward bookmarklet.

    Say you come across a website, see a few pretty cool effects (right click to ensure it’s not Flash driven) and you’d like to know which of the some three fabulous JavaScript frameworks (MooTools, Yahoo User Interface, jQuery, the infamous Scriptaculous, Dojo Toolkit, Mochikit, etc.) are being used to rise the magic.

    Typically, you’d have to look for the script tag in the source. Well forget about it, now you have WTFramework – one click and a info pops–up informing which framework are we dealing with.

    http://blog.olicio.us/2008/11/08/wtframework-bookmarklet/

    Tuesday, November 11, 2008

    WaveMaker

    The WaveMaker platform consists of two components: WaveMaker Visual Ajax Studio™ for developing rich internet applications and WaveMaker Rapid Deployment Server™ for deploying applications into a standard and secure Java environment.

    Truly WYSIWYG Web 2.0 Development
    WaveMaker Visual Ajax Studio is an easy-to-use visual builder that enables the drag & drop assembly of scalable, web-applications using Ajax widgets, web services and databases. WaveMaker Studio will look and feel especially familiar to client/server developers who are used to working with visual tools.

    WaveMaker has helped customers reduced development costs by 67% and cut the lines of code written by 98%. Less code makes WaveMaker applications cheaper to maintain and easier to manage.

    http://wavemaker.com/

    JS Frameworks

    Peppy
    Peppy is a lightning fast CSS 3 compliant selector engine with no external library dependencies. Peppy can be used along side other libraries seamlessly.
    As it stands now Peppy is faster1 than all other major JavaScript libraries with DOM querying capabilities (Prototype 1.6.0.3, JQuery 1.2.6, MooTools 1.2.1, EXT 2.2, DoJo 1.2.0, YUI 2.6.0). It is faster2 than Sizzle by John Resig and it also is cross browser (IE included). Take a look for yourselves, I have a profiling page set up here.
    At 10k it is an ideal replacement for other excellent but bulkier libraries (whose feature sets span beyond DOM querying) when features additional to DOM querying are not needed in your web application. If you are designing your own JavaScript library or want to replace your existing libraries selector engine then Peppy is an ideal candidate.
    http://jamesdonaghue.com

    Sizzle
    This is a new pure-JavaScript CSS selector engine that I'm working on. Comes in at roughly 4x faster in Firefox 3, 3x faster in Opera 9, 1.5x faster in Safari 3 than the other major JavaScript libraries. It's completely standalone (no library dependencies) and clocks in at 4KB.
    Currently this engine is expected to become the new default selector engine of jQuery, MochiKit, Prototype, and Dojo.
    http://github.com/jeresig/sizzle/tree/master

    Prototype
    Prototype is a JavaScript Framework that aims to ease development of dynamic web applications.
    Featuring a unique, easy-to-use toolkit for class-driven development and the nicest Ajax library around, Prototype is quickly becoming the codebase of choice for web application developers everywhere.
    http://www.prototypejs.org/

    jQuery
    jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.
    http://jquery.com/


    MooTools

    MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API.
    MooTools code respects strict standards and doesn't throw any warnings. It's extensively documented and has meaningful variable names: a joy to browse and a snap to understand.
    http://mootools.net

    Ext JS

    Ext JS is a cross-browser JavaScript library for building rich internet applications.

    • High performance, customizable UI widgets
    • Well designed, documented and extensible Component model
    • Commercial and Open Source licenses available
    http://extjs.com

    dojo
    Ajax, events, packaging, CSS-based querying, animations, JSON, language utilities, and a lot more. All at 26K (gzipped).
    http://dojotoolkit.org

    The Yahoo! User Interface Library
    The Yahoo! User Interface (YUI) Library is a set of utilities and controls, written in JavaScript, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX. The YUI Library also includes several core CSS resources.
    http://developer.yahoo.com/yui/

    MochaUI. A web applications user interface library

    MochaUI is a web applications user interface library built on the Mootools JavaScript framework.

    Uses:

    • Web Applications
    • Web Desktops
    • Web Sites
    • Widgets
    • Standalone Windows and Modal Dialogs
    http://mochaui.com/

    Monday, November 10, 2008

    Using mod_concat to Speed Up Start Render Times

    The most critical part of a page’s load time is the time before rendering starts. During this time, users may be tempted to bail, or try a different search result. For this reason, it is critical to optimize the head of your HTML to maximum performance, as nothing will be visible until it finishes loading the objects inside.

    One easy way to speed up rendering during this crucial time is to combine your CSS and JavaScript, saving the performance tax associated with every outbound request. While easy in theory, in practice this can be difficult, especially for large organizations.

    http://www.artzstudio.com/2008/08/using-modconcat-to-speed-up-render-start/

    Sunday, November 9, 2008

    SlickSpeed Selectors Test

    Speed/validity selectors test for frameworks

    Every framework runs in his own iFrame, thus no conflicts can happen. Tests are run selector by selector, with an interval to prevent the browser from freeezing.

    Tests are run in a neutral environment, no library or framework is included in the main javascript test, to avoid favoritism.

    http://jamesdonaghue.com/static/peppy/profile/slickspeed/

    The Best Cheat Sheets for Web Developers

    Cheat sheet is a reference tool that provides simple, brief instructions for accomplishing a specific task. We have collated a set of best cheat sheets for web developers. It includes some of the popular programming language, e.g. jQuery, Mootools, Prototype, PHP, MySQL and etc…

    http://www.webappers.com/2008/11/05/best-cheat-sheets-for-web-developers/

    The CouchDB Project

    Apache CouchDB is a distributed, fault-tolerant and schema-free document-oriented database accessible via a RESTful HTTP/JSON API. Among other features, it provides robust, incremental replication with bi-directional conflict detection and resolution, and is queryable and indexable using a table-oriented view engine with JavaScript acting as the default view definition language.

    Apache CouchDB is an effort undergoing incubation at The Apache Software Foundation (ASF), sponsored by the Apache Incubator PMC. Incubation is required of all newly accepted projects until a further review indicates that the infrastructure, communications, and decision making process have stabilized in a manner consistent with other successful ASF projects. While incubation status is not necessarily a reflection of the completeness or stability of the code, it does indicate that the project has yet to be fully endorsed by the ASF.

    http://incubator.apache.org/couchdb/index.html

    Tuesday, November 4, 2008

    How to observe more fields with AJAX helper

    The observe_field AJAX helper allows to observe one field; if there is a change, it calls the specified method on the server side. It is possible to attach one value for the call.

    This is enough if we have one text box search for searching over multiple columns or for a full-text search.

    For a more complicated filtering functionality with more fields there are two main problems with the observe_field helper:

    • how to specify more parameter values in the observe_field helper.
    • it is necessary to write a observe_field call for each field.
    http://www.valibuk.net/2006/08/how-to-observe-more-fields-with-ajax-helper/

    Wednesday, October 29, 2008

    Elements of Ruby Style

    Next week marks the publication of the 50th Anniversary edition of the Strunk & White's The Elements of Style, a critically important work for anybody who puts words together on a regular basis.

    In that spirit, here are some thoughts on good Ruby & Rails style -- I'm mostly focusing on Ruby-specific guidelines here. This is somewhat closer to a brain dump than a fully-baked style guide, so it's something I intend to come back to, especially after hearing everybody tell me exactly where I'm wrong, wrong, wrong.

    UPDATE: There were some comments about the formatting being messed up. Apparently whatever tool we're using for code coloring doesn't work well with Safari. In Firefox, the formatting is as intended. We've cleaned this up -- thanks for your patience.

    The goals of well-styled code are correctness and simplicity, in that order.

    I don't want to pretend that it's not important for code to be correct. Still, I think that functionally correct code is not the last step. For me, the best order is: Make it Work, Make it Clean, Make it Fast (if necessary).

    Ruby code should be indented two spaces.

    This should be uncontroversial, right? Indenting Ruby code four spaces indicates that you are a very recent convert from Java.

    Statements that extend past 80 characters or so should be broken up and indented on the following line.

    This one may be a little idiosyncratic, since I tend to use a narrower edit window than a lot of people. That said, it's still a good idea to have a hard right margin to your code. Whether it's 80 or 100 characters is less relevant than that all of the code can fit on the screen without scrolling. If you have to scroll to see code, eventually, you'll make mistakes based on code that you can't all see at once. (I find this especially true in HTML/ERb, where you can easily mangle a closing tag in column 125 and lose your mind trying to find the problem).

    In either case, you should never break up individual sub statements -- in the above examples, never split up a + b -- you should try to keep entire expression, hash or array arguments on the same line even if that means the line above is shorter.

    Anyway, both choices have tradeoffs. The double-indent is the easiest to maintain as the code changes, but can make it tricky to follow the logical structure of the code. The longer indent makes it generally clear what goes together, but it's a little hard to keep up, and can look kind of ragged.

    I tend to prefer the first form for Ruby, although I do use the second sometimes, especially for, say, hash options inside a larger statement.

    Ruby allows you to leave out parenthesis, in general, resist this temptation.

    Parenthesis make the code easier to follow. General Ruby style is to use them, except in the following cases:

    • Always leave out empty parentheses
    • The parentheses can be left out of a single command that is surrounded by ERb delimiters -- the ERb markers make sure the code is still readable
    • A line that is a single command and a single simple argument can be written without the parenthesis. Personally, I find that I do this less and less, but it's still perfectly readable. I tend not to like single lines in regular ruby code that have multiple arguments and no parentheses.
    • A lot of Ruby-based Domain Specific Languages (such as Rake) don't use parenthesis to preserve a more natural language feel to their statements.
    http://www.pathf.com/blogs/2008/10/elements-of-ruby-style/

    typeface.js

    Instead of creating images or using flash just to show your site's graphic text in the font you want, you can use typeface.js and write in plain HTML and CSS, just as if your visitors had the font installed locally. This is a work in progress, but functional enough at least to render the the graphic text on this site.

    http://typeface.neocracy.org/

    Tuesday, October 28, 2008

    Ruby for Symbian OS

    Symbian is releasing Ruby for Symbian OS to the Open Source software developer community.

    Ruby for Symbian OS brings the power of the Ruby programming language to the Symbian ecosystem under the terms of this Licence Agreement.

    https://developer.symbian.com/main/community/open_source_projects/ruby/index.jsp

    A strftime for Prototype

    Object.extend(Date.prototype, {
    strftime: function(format) {
    var day = this.getUTCDay(), month = this.getUTCMonth();
    var hours = this.getUTCHours(), minutes = this.getUTCMinutes();
    function pad(num) { return num.toPaddedString(2); };

    return format.gsub(/\%([aAbBcdDHiImMpSwyY])/, function(part) {
    switch(part[1]) {
    case 'a': return $w("Sun Mon Tue Wed Thu Fri Sat")[day]; break;
    case 'A': return $w("Sunday Monday Tuesday Wednesday Thursday
    Friday Saturday"
    )[day]; break;
    case 'b': return $w("Jan Feb Mar Apr May Jun Jul Aug Sep Oct
    Nov Dec"
    )[month]; break;
    case 'B': return $w("January February March April May June July
    August September October November December"
    )
    [month]; break;
    case 'c': return this.toString(); break;
    case 'd': return this.getUTCDate(); break;
    case 'D': return pad(this.getUTCDate()); break;
    case 'H': return pad(hours); break;
    case 'i': return (hours === 12 || hours === 0) ? 12 :
    (
    hours + 12) % 12; break;
    case 'I': return pad((hours === 12 || hours === 0) ? 12 :
    (hours + 12) % 12); break;
    case 'm': return pad(month + 1); break;
    case 'M': return pad(minutes); break;
    case 'p': return hours > 11 ? 'PM' : 'AM'; break;
    case 'S': return pad(this.getUTCSeconds()); break;
    case 'w': return day; break;
    case 'y': return pad(this.getUTCFullYear() % 100); break;
    case 'Y': return this.getUTCFullYear().toString(); break;
    }
    }.bind(this));
    }
    });

    http://alternateidea.com/blog/articles/2008/2/8/a-strftime-for-prototype

    Safary 3+ CSS

    Add to head block:
    link type="text/css" media="screen and (-webkit-min-device-pixel-ratio:0)" href="/css/safari.css"

    Monday, October 27, 2008

    Disabling the Image Toolbar in IE 6+

    To disable the image toolbar for a particular page on your website, simply add the following META tag to the HEAD section of your HTML document:

    < meta_equiv="imagetoolbar" content="no">

    The "no" setting disallows the toolbar.

    Disabling the Toolbar on an Image by Image Basis

    If you only want to prevent the toolbar from appearing for certain graphics on your page, you can disable it on an image by image basis.

    For example, if you have a picture called "proprietary.gif", you can add a GALLERYIMG attribute to the image tag that you used to display it:

    < img_src="proprietary.gif" galleryimg="no">

    The "no" prevents the toolbar from showing. Setting it to "yes" allows the toolbar, and is useful if you have set the entire page to default to not showing the toolbar, and only want to enable it on an image by image basis.

    Limitations

    Note that disabling the image toolbar does not actually prevent visitors from saving your images, sending them to others or printing them. It merely disables the toolbar. Period. It is not a solution to theft of your graphics. Visitors can still right click the mouse on your pictures and save them from the right click menu, or save the entire page with all the images to their disk, etc (the list of ways to do this is very long). However, it is still useful for people who prefer not to have the toolbar pop out on the pictures appearing on their website. In fact, judging by the response of one very irritated IE user, who called the toolbar "that stupid IE image popup", you may even be doing your visitors a service.