Jquery: creating plugins


    yourPluginName: function(options) {
      var defaults = {
        yourDefaults: 'here',
                   anotherDefault:  ‘here’
              // This way, what you pass as args overwrite your defaults:
      var options =  $.extend(defaults, options);
      // ...And then, your functionality here...

HTML5: Form fields

New attributes:



oninput="updateMessage(this)" /* You can run custom JS on input */

autocomplete=”on”  // Remembers what the users enter in the field before, and makes it available for autofill. If you want to create your own list of autofill values:

Choose an animal:  <input type="text" name="animal" list="animals" /><br />
  <datalist id="animals">
   <option value="Moneky">
   <option value="Donkey">

<input type="tel" name="phone" required /> /* Handle phones */
<input type="email" name="email"  /> /* Emails */
<input placeholder="enter your 5 digit id number" type="text"
    name="idNumber" pattern="[0-9]{5}" /> /* You can customize your own patterns */
<input type="number" name="quantity" min="1" max="50" value="" /> /* You can validate numbers this way */
<input type="date"  min="2012-03-12" step="1"
                         max="2012-05-12" name="departingDate" /> /* Produces a calendar pick for you */

<input type="range" name="shoeSize" min="0" max="15" step=".5" 
value="3" /> /* Produces a range scale */
<meter value="3" min="0" max="10"></meter><br /> /* Displays percentages in a meter kind of graph */

<progress value="35" max="100" >
</progress> /* Display a progress bar */

node.js: API

global — The equivalent of window in the browser.

process.nextTick(cbfunction); // Schedule a function callback for the next time the loop goes around

console.log and console.error // Same as in firebug




node.js: how it is different from other web platforms

Node has a single thread, looping on itself to handle requests. Unlike PHP and other platforms, where each request spawn its own thread.

This means: if a request modify a variable with global scope, the modified variable will be served in the next request.

Node process in a nutshell:

loop taking request (running in infinite recursion) > request inn > asynchronous event spawn to handle the request > when the process the event spawn is done, it calls back the loop > request is returned

Because of that architecture, the things you need to avoid are:

1) Blocking I/O processes. Try to trigger events instead.

2) Unhandled error exceptions. Since you are sharing the thread with all the other requests, it can really make your app unstable.

In general, you are going to choose node.js because your app needs to handle lots of I/O concurrent events. If each (or some of those events) take a long time (more than 500ms) to handle, what we call CPU intensive or blocking I/O operations, you may be better off with other more traditional languages.


Rails and devise: building associations at record creation time

In your “create” method, on your controller:

@search =[:search])


  • current_user contains your user record (via devise)
  • search, searches is the model of the record you are trying to create
  • build is just there to marshal your posted form parameters, so no need to include them (RoR is magical like that)
  • current_user.searches is building the relationship between those two, so the search you are creating will have the associated user_id on it

So your User model:

has_many :searches, dependent: :destroy

And your Searches model:

belongs_to :user

This is the very basic association operation. For more details and the list of all possible combinations you can form (from the source):




Python: control structures

a = [0, 1, ‘hello’, ‘python’]
for i in a:
print i

for i, j in enumerate(a):
print i, j // Same as above, but prints the index

while i < 10:
i = i + 1

break and continue can be used to break out of the list

if i == 0:
print ‘zero’
elif i == 1:
print ‘one’
print ‘other’

if i == 0 or (i == 1 and i + 1 == 2):

    print ‘0 or 1’

Try / Catch statements:

a = 1 / 0
except Exception, e:
print ‘oops: %s’ % e
print ‘no problem here’
print ‘done’

You can have more than one except statement (for different kinds of exceptions)



Node.js: the basics

Install node.js (no need to be verbose, see website for more details)

$ node -v // Verify installation

Install the NPM (node package manager, this will allow you to install and manage node packages):
$ curl | sh

$ npm –version // Verify version and installation of package manager

Creating your application and installing packages:

$ mkdir my-project/

$ cd my-project/

$ npm init --yes

$ npm install colors

Now you will see inside your directory the node_modules folder, and inside of it, the package “color” you have recently installed.

To use the newly installed package:

$ vi index.js

And then, inside index.js, type:

require(‘colors’); // Will include the package 'colors', and now you can use it as in the line below

console.log(‘smashing node’.rainbow);

To manage / import modules into your own project, you will need a package.json file in the root directory of it, something like:


    “name”: “my-colors-project”,

    “version”: “0.0.1”, // Notice how first versions in node start at 0.0.1,

    “dependencies”: {

      “colors”: “0.5.0” // The modules you need to export to make your module



Modules installed this way end up inside your ./node_modules/ file, but you can also have relative modules, not installed inside node_modules, you just have to specify the local path to them.

Once that is setup, run:

$ npm install // Will fetch dependencies for you

$ npm publish // To make your package available for others to install.

Installing binary utilities is a bit different. For example, to install the express framework:

$ npm install -g express

And then, to create a site using express:

$ mkdir my-site

$ cd mysite

$ express

To search for available packages:

$npm search realtime // Search for the realtime package

To get more information about the package you just discover:

$ npm view realtime


An alternative way to do this:

$sudo npm install -g express@2.5.4 (or whatever version you need)

$expression your_app_name  // Expression is the framework

$cd your_app_name && npm install // That will install dependencies specified in the package.json manager. You can modify that file if you need more dependencies

$node app // Start your app at port 3000

After this, everything happens inside app.js, that is the file that will serve your app
Heroku Rails

Heroku: handy, useful commands

// In case errors happen…

$ heroku logs –tail 

$ git push heroku master // Push local changes

$  heroku run rake db:migrate // Push your new local db migrations to Heroku

Heroku Rails

Ruby On Rails: barebones site template from the ground up.

We are talking about quick demos, site bootstraping kind of deal here. So don’t expect robust, detailed explanations.

Also, assuming you have Ruby / Rails / Git / postgresql / RVM (optional) installed. Barebones, cutting through most of the commands explanations. Aim to push site and ideas fast out there.

$rails new first_app -d postgresql

-d postgresql to create this with postgres

NOTE: postgresql (and role creation) have some issues. It is not a straight process, you can always default to the mysql default in your local server, and harden it on production (if saving time in a demo is an issue).

To secure your app, create a role for the postgres database specific to your app.

In your postgres admin, click on the Login Roles, add Login Role. Make sure the new role can create database objects. Make sure you set a password for it as well.

Then, in config/database.yml you need to plugin the username / password you just created  ( in all the diff databases: development, test and production)

Modify your gem file as follows

$bundle install –without production –binstubs

binstubs makes it easier to run tests later (the command is shorter). It stores binaries so they don’t have to be pre-compiled everytime you run tests.

Speaking of tests, at this point you can generate the skeleton to run tests:

$rails generate cucumber:install
$rails generate rspec:install

$rake db:create

$rails server // just to make sure you have a local server setup

$git init

$git add .

$git commit -m “Initial commit”

[optional] Create a bitbucket (or github) repo:

git remote add origin
git push -u origin --all # to push up the repo for the first time

Download and install heroku toolbelt (if not there yet)

$heroku login

$heroku create [name of your app here]// inside your app’s directory

// Create the basic model for your users:

$rails generate scaffold User first_name:string last_name:string

// By convention, rails likes models to be singular, and camel cased (starts with a capital letter). As in “User”

// At this point, you should have the basic CRUD operations for users at:


// To create the user’s authentication stuff:

$ rails generate devise:install

// And follow the instructions printed afterwards (no need to replicate them here)

$ rails generate devise User

$ rails generate devise Admin

// Important! protect your user’s section by adding the following to app/controllers/users_controller.rb:

before_filter :authenticate_admin!

// And also, make sure users can’t register as admins (inside the admin’s model, app/models/admin.rb)

devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable

// Notice that :registerable has been removed. If you need to create admins, you will have to do it via direct db access, or by using the console and bypassing momentarily that restriction, or, you can bring it back and ask for an extra token at admin registration time, but then you will have to manage / distribute those tokens

$bundle exec rake db:migrate // Update the DB with it

$ rails generate controller StaticPages home help about contact_us–no-test-framework // Create home and help pages, which can contain dynamic variables. It generates all your views and controllers

– Modify your public/index.html with something other than the default Rails page (or remove it if you are sending users to another page via the router)

root to: ‘static_pages#home’ // redirects “/” to static pages controller, home method

match ‘/help’, to: ‘static_pages#help’ // redirects to help page

– Put any other pure static pages in this directory as well (public/hello.html, etc)

Example of how to integrate the login and signup links in a view after devise is in place:

<% unless admin_signed_in? -%>
  <p><%= link_to ‘Sign up as Admin’, new_admin_registration_path %></p>
  <p><%= link_to ‘Sign in as Admin’, new_admin_session_path %></p>
<% end -%>
<% unless user_signed_in? -%>
  <p><%= link_to ‘Sign up as User’, new_user_registration_path %></p>
  <p><%= link_to ‘Sign in as User’, new_user_session_path %></p>
<% end -%>
<% if user_signed_in? -%>
  <p><%= link_to ‘Token Authentication Example’, token_path(:auth_token => current_user.authentication_token) %></p>
<% end -%>

Example of how to protect your pages from access (via the controller):

before_filter :authenticate_user!


before_filter :authenticate_admin!

$rails generate scaffold Micropost content:string user_id:integer // Create an object that will be associated with a user

// Setup your basic models associations at this point:

class User < ActiveRecord::Base // Inside apps/model/user.rb
attr_accessible :email, :name
has_many :microposts

class Micropost < ActiveRecord::Base // Inside apps/model/micropost.rb
attr_accessible :content, :user_id

belongs_to :user

validates :content, :length => { :maximum => 140 }

// Next, save the changes, and push them locally and in Heroku:

$ git add .

$ git commit -m “Add models”

$ git push heroku master

$ heroku run rake db:migrate

$ heroku open // Make sure things are handy dandy

//  A bit of automatic styling

app/assets/stylesheets/custom.css.scss // Add this file, with the following line:

@import “bootstrap”; // Now you can use twitter’s bootstrap to style your app!

jquery mobile

Jquery mobile: the basics

Basic page structure:

<div data-role=”page”>

<div data-role=”header”></div>

<div data-role=”content”></div>

<div data-role=”footer”></div>



Since links are internal (load a different part of your template), in order to call real external links, you need:

Rel=”external” or data-ajax=”false”

To implement a back button, you do:


To implement dialogs (modals) instead of opening the page:

data-rel=”dialog”, data-rel="back" (to close it)

To load an external page:

$.mobile.loadPage(pageurl); // Be careful with this one: you have limited resources in the mobile platform!

Flipping through pages:

$.mobile.changePage(to, transition, back, changeHash)

to = the destination page

changeHash = the new URL once you go to the new page

Example of implementation:

<a href=”javascript:toAbout()”>About</a>

function toAbout() {
$.mobile.changePage( “about.html”, { transition: “pop”} );

You can also change pages via buttons:

<a data-role=”button” href=”#page2″>Page Navigation</a>

Where #page2 points to the page you defined in as <div data-role=”page” id=”page2″>Page content here</div>

<a data-role=”button” href=”#dialog1″  data-rel=”dialog” data-transition=”pop”>Open Dialog </a>


You can specify them via the data-theme attribute:

<header data-role=”header” data-theme=”b”>

The barebones template here: