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