Wednesday, 26 June 2013

reset

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
/* remember to define focus styles! */
:focus {
outline: 0;
}
body {
line-height: 1;
color: black;
background: white;
}
ol, ul {
list-style: none;
}
/* tables still need 'cellspacing="0"' in the markup */
table {
border-collapse: separate;
border-spacing: 0;
}
caption, th, td {
text-align: left;
font-weight: normal;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: "";
}
blockquote, q {
quotes: "" "";
}
view raw a.rb hosted with ❤ by GitHub

Tuesday, 25 June 2013

Single Table Inheritance in Rails


I couldn’t find too much information on Rails awesome built in Single Table Inheritance so I thought I’d write this up for anyone who is interested.
What is Single Table Inheritance?
In a nutshell, STI allows you to create subclasses of a particular database table. Using a single table, you can cast rows to specific objects that extend the base model.
How to create STI relationships in Rails
Lets say we have a model Computer
class Computer < ActiveRecord:Base
  # in app/models
  # Fields:
  #   String name
  #   String owner
  #   String manafacturer
  #   String color

  def default_browser
    "unknown!"
  end 
end
Now, we want to differentiate between Macs and PCs. It doesn’t really make sense to make a different table for each, since they both have pretty much the same columns. Instead we can create a new column, type, which tells Rails to use STI on Computer. Lets look at what the models might look like.
class Computer < ActiveRecord:Base
  # in app/models
  # Fields:
  #   String name
  #   String owner
  #   String manafacturer
  #   String color
  #   String type

  def default_browser
    "unknown!"
  end 
end

class Mac < Computer
  # in app/models
  # this is for Computers with type="Mac"
  before_save :set_color

  # Lets say all macs are silver, no point setting these ourselves
  def set_color
    self.color = "silver"
    self.manafacturer = "apple"
  end

  # Lets overwrite the default_browser method
  def default_browser
    "safari"
  end
end

class PC < Computer
  # in app/models  

  # Lets overwrite the default_browser method
  def default_browser
    "ie =("
  end
end
Anytime Rails opens up the computer object, it looks for the subclass corresponding to type. For instance,type="CoolComputer" corresponds to model CoolComputer < Computer.
How to use STI Models
To create a new mac, you can do:
m = Mac.new
m.name = "kunal's mac"
m.owner = "kunal"
m.save
m # => #<Mac id: 1, name: "kunal's mac", owner: "kunal", manafacturer: "apple", color: "silver", type: "Mac", ...>
Whats even cooler is ActiveRecord queries. Lets say we want all the computers
Computer.all # => [#<Mac id: 1, name: "kunal's mac", owner: "kunal", manafacturer: "apple", color: "silver", type: "Mac", ...>, #<Mac id: 2, name: "anuj's mac", owner: "anuj", manafacturer: "apple", color: "silver", type: "Mac", ...>, #<PC id: 3, name: "bob's pc", owner: "bob", manafacturer: "toshiba", color: "blue", type: "PC", ...>]
Yup, it automatically gives you the correct objects! You can find out the type of a particular object by calling.typeis_a? or .class
Computer.first.type == Mac # true
Computer.first.is_a? Mac # true
Computer.first.class == Mac # true
If we only want Macs, we can do
Mac.all
Custom Inheritance Column
If you want to use another column instead of type to use for STI, you can simply add this to the top of your model:
set_inheritance_column 'whatever_you want'
Note: If you have a database column named type, you can turn off Single Table Inheritance by changing the inheritance column to something other than type.
Organizing This in Rails
After using STI, I ended up with a bloated models folder because all of the many custom sub models I created were in the models folder. To solve this, I created a folder in models to store all of my computer specific models
* app
*   models
*     computer.rb
*     computers
*       pc.rb
*       mac.rb
Rails doesn’t automatically open subfolders in the models folder, so I added in config/application.rb:
# Load Subfolder Models
config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
Cheers,
Kunal


http://blog.thirst.co/post/14885390861/rails-single-table-inheritance

Wednesday, 19 June 2013

def Κοτόπουλο

# encoding: UTF-8
def παρακαλώ
"please"
end
def Κοτόπουλο
"chicken"
end
def ∑(iterable)
iterable.reduce(&:+)
end
puts [ ∑([1, 2]), Κοτόπουλο, παρακαλώ].join(' ')

Saturday, 15 June 2013

Friday, 14 June 2013

Open a new Mac OS X terminal window or tab in the current dir

#!/bin/sh
#
# Open a new Mac OS X terminal window or tab in the current or another
# directory and optionally run a command in the new window or tab.
#
# - Without any arguments, the new terminal window opens in
# the current directory, i.e. the executed command is "cd $PWD".
# - If the first argument is a directory, the new terminal will "cd" into
# that directory before executing the remaining arguments as command.
# - The optional "-t" flag executes the command in a new tab
# instead of a new window.
# - The optional "-x" flag closes the new window or tab
# after the executed command finishes.
# - The optional "-p" flag takes an argument of the form x,y (e.g. 40,50) and
# positions the terminal window to the indicated location on the screen
# - The optional "-s" flag takes an argument of the form w,h (e.g. 800,400) and
# resizes the terminal window to the indicated width and height in pixels.
#
# Written by Marc Liyanage <http://www.entropy.ch>
#
# Version 2.1
#
set -e
while getopts xtp:s: OPTION; do
[ $OPTION = "x" ] && { EXIT='; exit'; }
[ $OPTION = "t" ] && { TAB=1; }
[ $OPTION = "p" ] && { POSITION="set position of window 1 to {$OPTARG}"; }
[ $OPTION = "s" ] && { SIZE="set size of window 1 to {$OPTARG}"; }
done
for (( $OPTIND; $OPTIND-1; OPTIND=$OPTIND-1 )); do shift; done
view raw gistfile1.txt hosted with ❤ by GitHub
in ~/.profile

Thursday, 13 June 2013

Avoid `console` errors in browsers that lack a console.

// Avoid `console` errors in browsers that lack a console.
if (!(window.console && console.log)) {
(function() {
var noop = function() {};
var methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'markTimeline', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];
var length = methods.length;
var console = window.console = {};
while (length--) {
console[methods[length]] = noop;
}
}());
}

AngularJS_generator




##Install yo npm install -g yo grunt-cli bower

##AngularJS generator npm install -g generator-angular

##Make a new directory, and cd into it: mkdir AngularJS_generator && cd $_

##Run yo angular, optionally passing an app name: yo angular AngularJS_generator

Route

Generates a controller and view, and configures a route in app/scripts/app.js connecting them.

Example:

yo angular:route myroute

Produces app/scripts/controllers/myroute.js:

angular.module('myMod').controller('MyrouteCtrl', function ($scope) {
  // ...
});

Produces app/views/myroute.html:

<p>This is the myroute view</p>

Controller

Generates a controller in app/scripts/controllers.

Example:

yo angular:controller user

Produces app/scripts/controllers/user.js:

angular.module('myMod').controller('UserCtrl', function ($scope) {
  // ...
});

Directive

Generates a directive in app/scripts/directives.

Example:

yo angular:directive myDirective

Produces app/scripts/directives/myDirective.js:

angular.module('myMod').directive('myDirective', function () {
  return {
    template: '<div></div>',
    restrict: 'E',
    link: function postLink(scope, element, attrs) {
      element.text('this is the myDirective directive');
    }
  };
});

Filter

Generates a filter in app/scripts/filters.

Example:

yo angular:filter myFilter

Produces app/scripts/filters/myFilter.js:

angular.module('myMod').filter('myFilter', function () {
  return function (input) {
    return 'myFilter filter:' + input;
  };
});

View

Generates an HTML view file in app/views.

Example:

yo angular:view user

Produces app/views/user.html:

<p>This is the user view</p>

Service

Generates an AngularJS service.

Example:

yo angular:service myService

Produces app/scripts/services/myService.js:

angular.module('myMod').factory('myService', function () {
  // ...
});

Options

There are options for each of the methods for registering services. For more on using these services, see the module API AngularJS documentation.

Factory

Invoked with --factory

This is the default method when creating a service. Running yo angular:service myService --factory is the same as running yo angular:service myService

Service

Invoked with --service

Value

Invoked with --value

Constant

Invoked with --constant

Options

In general, these options can be applied to any generator, though they only affect generators that produce scripts.

CoffeeScript

For generators that output scripts, the --coffee option will output CoffeeScript instead of JavaScript.

For example:

yo angular:controller user --coffee

Produces app/scripts/controller/user.coffee:

angular.module('myMod')
  .controller 'UserCtrl', ($scope) ->

A project can mix CoffeScript and JavaScript files.

Minification Safe

By default, generators produce unannotated code. Without annotations, AngularJS's DI system will break when minified. Typically, these annotations the make minification safe are added automatically at build-time, after application files are concatenated, but before they are minified. By providing the --minsafe option, the code generated will out-of-the-box be ready for minification. The trade-off is between amount of boilerplate, and build process complexity.

Example

yo angular:controller user --minsafe

Produces app/controller/user.js:

angular.module('myMod').controller('UserCtrl', ['$scope', function ($scope) {
  // ...
}]);

Background

Unannotated:

angular.module('myMod').controller('MyCtrl', function ($scope, $http, myService) {
  // ...
});

Annotated:

angular.module('myMod').controller('MyCtrl',
  ['$scope', '$http', 'myService', function ($scope, $http, myService) {

    // ...
  }]);

The annotations are important because minified code will rename variables, making it impossible for AngularJS to infer module names based solely on function parameters.

The recommended build process uses ngmin, a tool that automatically adds these annotations. However, if you'd rather not use ngmin, you have to add these annotations manually yourself.

Bower Components

The following packages are always installed by the app generator:

  • angular
  • angular-mocks
  • angular-scenario

The following additional modules are available as components on bower, and installable via bower install:

  • angular-cookies
  • angular-loader
  • angular-resource
  • angular-sanitize

All of these can be updated with bower update as new versions of AngularJS are released.

Configuration

Yeoman generated projects can be further tweaked according to your needs by modifying project files appropriately.

Output

You can change the app directory by adding a appPath property to bower.json. For instance, if you wanted to easily integrate with Express.js, you could add the following:

{
  "name": "yo-test",
  "version": "0.0.0",
  ...
  "appPath": "public"
}

This will cause Yeoman-generated client-side files to be placed in public.

Testing

For tests to work properly, karma needs the angular-mocks bower package. This script is included in the bower.json in the devDependencies section, which will be available very soon, probably with the next minor release of bower.

While bower devDependencies are not yet implemented, you can fix it by running:

bower install angular-mocks

By running grunt test you should now be able to run your unit tests with karma.

Contribute

See the contributing docs

When submitting an issue, please follow the guidelines. Especially important is to make sure Yeoman is up-to-date, and providing the command or commands that cause the issue.

When submitting a PR, make sure that the commit messages match the AngularJS conventions.

When submitting a bugfix, write a test that exposes the bug and fails before applying your fix. Submit the test alongside the fix.

When submitting a new feature, add tests that cover the feature.

Folked: https://github.com/yeoman/generator-angular

License

BSD license

view raw README.md hosted with ❤ by GitHub
DOWNLOAD repo

 https://github.com/msroot/AngularJS_generator/

TESTING

sudo npm install -g karma


Start the server (it runs on node.js)
karma start
Another tab
karma run


➜  AngularJS_generator git:(master) karma run
Chrome 27.0 (Mac): Executed 6 of 6 SUCCESS (0.155 secs / 0.038 secs)
➜  AngularJS_generator git:(master) 

Tuesday, 11 June 2013

Fixing recruitment

The recruitment industry is hilariously broken. It's hard enough for me, a full-time developer, to determine if someone else is a good programmer, so how could I expect a recruiter who has no skills in programming to do it? I'm paying for someone to perform what is essentially keyword matching heuristics between my job description and a candidate’s resume. This process is poor at best with the opportunity to go stupidly wrong (like when I get sent Java developers for a JavaScript position).
You can make the argument that recruiters are there as a first pass filter, to strip out all the people that apply for jobs regardless of whether their skills match. At around 20% of what I'm going to pay for someone's salary, that's an expensive filter.
On top of that, don't forget about the incentive structure where recruiters are encouraged to place as many people as possible, as quickly as possible – the recruitment "numbers game".
In their defence, recruiters make the argument that their profession is one of human relations. Please. If that was really true, why are they almost universally despised? Why are so many “recruitment professionals” failing at the one skill they really need to have?
It comes down to one problem: transparency. A lack of transparency about who you'll be working for. A lack of transparency on how much the recruiter is being paid. Recruiters control information. Try submitting your CV to them as a PDF and watch them bounce it back wanting a Word version so they can remove your details from it before sending it off to a client.
Fixing recruitment requires introducing transparency. If you want to differentiate from all the other people in recruitment, then make your dealings transparent and provide value in other areas – such as actually determining if someone is good! With Dragonfly we're trying
change happen for full-time recruitment.
SAMUEL RICHARDSON

Socket.io-example repo

https://github.com/msroot/Socket.io-example

Tuesday, 4 June 2013

Ember.JS Resources

https://gist.github.com/harisadam/5046520/raw/2558636546bc0cd52314a73e6d62a786e402bd32/Ember.js+resources.md



# Ember.js #
[Follow Me on twitter](http://twitter.com/harisadam)

##Deprecated, I recommend emberwatch.com, you will find very usefull stuff

##Videos:##

* Architecture overview (old) - http://www.mochaleaf.com/blog/ember-js-revised-architecture-overview/
* Intro to ember.js and the new router api - http://toranbillups.com/blog/archive/2013/01/03/Intro-to-ember-js-and-the-new-router-api/
* Peepcode Fire Up Ember.js - https://peepcode.com/products/emberjs
* Seattle Ember.js Meetup Part 1 (Tom Dale - Ember Data) - http://www.youtube.com/watch?v=_6yMxU-_ARs
* Seattle Ember.js Meetup Part 2 (Tom Dale - Ember Data Q&A) - http://www.youtube.com/watch?v=TTy1pbXdKJg
* Seattle Ember.js Meetup Part 3 (Yehuda Katz - Ember Router) - http://www.youtube.com/watch?v=4Ed_o3_59ME
* Seattle Ember.js Meetup Part 4 (Yehuda & Tom - Q&A) - http://www.youtube.com/watch?v=aBvOXnTG5Ag
* Ember.js Code-Walkthrough - http://lukaszielinski.de/blog/posts/2013/02/23/ember-dot-js-code-walkthrough-video/
* Getting Started with Ember.js - http://andymatthews.net/read/2012/06/19/Getting-Started-with-Ember.js-slides-and-video-now-available
* EmberCamp video channel - https://addepar.com/ember
* Ember-EasyForm & Ember-Validations - https://www.youtube.com/watch?v=ZWUjlbN8fvA&feature=player_embedded
* RailsCast Emberjs episode 1 - http://railscasts.com/episodes/408-ember-part-1
* RailsCast Emberjs episode 2 - http://railscasts.com/episodes/410-ember-part-2
* Ember Inspector: Live Controllers - https://www.youtube.com/watch?v=18OSYuhk0Yo&hd=1


##Posts:##

* Ember guides - http://emberjs.com/guides/
* Ember blog - http://emberjs.com/blog/
* Ember API - http://emberjs.com/api/
* Ember Data Architecture - https://github.com/emberjs/data/blob/master/ARCHITECTURE.md
* Breaking Changes - https://github.com/emberjs/data/blob/master/BREAKING_CHANGES.md
* Handlebars documentation - http://handlebarsjs.com/
* Understanding Ember.Object - http://www.cerebris.com/blog/2012/03/06/understanding-ember-object/
* Introducing Ember-EasyForm - http://reefpoints.dockyard.com/ember/2013/02/21/ember-easy-form.html
* Speaking With the Ember.js Core Team - http://net.tutsplus.com/articles/interviews/ember-js-core-team-interview/
* Building an Ember app with RailsAPI - Part 1 (coffeesript + rails) - http://reefpoints.dockyard.com/ember/2013/01/07/building-an-ember-app-with-rails-api-part-1.html
* Building an Ember app with RailsAPI - Part 2 (coffeesript + rails) - http://reefpoints.dockyard.com/ember/2013/01/09/building-an-ember-app-with-rails-api-part-2.html
* Building an Ember app with RailsAPI - Part 3 (coffeesript + rails) - http://reefpoints.dockyard.com/ember/2013/01/10/building-an-ember-app-with-rails-api-part-3.html
* Using Rails & Devise with Ember.js - http://say26.com/using-rails-devise-with-ember-js
* Documenting our understanding of EmberJS Data - https://gist.github.com/BernardNotarianni/4283607
* Introduction to Ember - http://www.embertraining.com/
* Getting Started With Ember.js - http://twbrandt.github.com/
* Why Discourse uses Ember.js - http://eviltrout.com/2013/02/10/why-discourse-uses-emberjs.html
* EMBER.JS DASHBOARD - http://code418.com/ember.js-dashboard/
* Ember Wrap-up - http://bradleypriest.com/tags.html#ember-wrapup-ref
* darthdeus vs Ember.js - http://darthdeus.github.com/
* Advice on & Instruction in the Use Of Ember.js - http://trek.github.com/
* Game On: Backbone and Ember - http://net.tutsplus.com/tutorials/javascript-ajax/game-on-backbone-and-ember/
* Use Ember.js as a cross plaform javascript library part 1 - http://cgcardona.github.com/2013/02/18/use-emberjs-as-a-cross-plaform-javascript-library/
* Use Ember.js as a cross plaform javascript library part 2 - http://cgcardona.github.com/2013/02/18/use-emberjs-as-a-cross-plaform-javascript-library-pt2/
* 5 Useful Tips for Ember.js Developers - http://say26.com/five-useful-tips-for-ember-js-developers
* Ember.js and Rails Authentication Gotchas - http://blog.waymondo.com/2012-12-18-ember-dot-js-and-rails-authentication-gotchas/
* Getters and Setters in Ember.js - http://emberashes.com/blog/2012/12/23/getters-and-setters-in-ember-dot-js/
* Ember.js Routing - the Director's Cut - http://www.thesoftwaresimpleton.com/blog/2012/08/20/routing_update/
* Ember.js forms made easy with EasyForm - http://thechangelog.com/emberjs-forms-made-easy-with-easyform/
* Rails + Ember.js http://www.devmynd.com/blog/2013-3-rails-ember-js
* Debugging Emberjs And Ember data - http://www.akshay.cc/blog/2013-02-22-debugging-ember-js-and-ember-data.html
* EmberJS Confuses Me - http://wekeroad.com/2013/03/06/ember-confuses-me
* 33 Great Resources to Get Started with Ember.js - http://accidentaltechnologist.com/javascript/33-great-resources-get-started-emberjs/
* Adding Splash Screen to an Ember.js App - http://www.harimenon.com/blog/2013/03/13/adding-splash-screen-to-an-ember-dot-js-app/
* EmberPress - A Letterpress clone in EmberJS - http://emberpress.eviltrout.com/
* Debugging EmberJS and Ember Data - http://www.akshay.cc/blog/2013-02-22-debugging-ember-js-and-ember-data.html

##Presentations:##

* Writing Big (ambitious) Apps Using - http://www.rvl.io/shex/ember/
* EMBER.JS & CLIENT SIDE VALIDATIONS - http://www.rvl.io/bcardarella/ember-js-and-clientsidevalidations
* Why Ember? - http://mutewinter.github.com/why_ember/#/slides
* Optimizing an API for Ember Data - https://speakerdeck.com/dgeb/optimizing-an-api-for-ember-data

##Interesting repositories: ##

* Ember auth - https://github.com/heartsentwined/ember-auth
* Ember-inspector - https://github.com/stefanpenner/ember-inspector
* Query string support for the Ember.js router - https://github.com/alexspeller/ember-query
* Ember.js Contacts List example - https://github.com/ivanvanderbyl/contacts
* Ember TODO example - https://github.com/Skalar/ember_todo
* Internationalization for Emberjs - https://github.com/jamesarosen/ember-i18n
* Experiment building Ember.js apps using RailsAPI - https://github.com/bcardarella/ember-railsapi
* A simple Rails app for testing CRUD with ember.js and ember-data.js - https://github.com/dgeb/ember_data_example
* EmberJS example App with a common CRUD interface - https://github.com/GerritWanderer/ember_data-crud_example
* Modal CRUD example - http://jsbin.com/ixigez/2/edit

How to try out the Ember Inspector in Google Chrome


by Kasper Tidemann

Yehuda Katz has been working on Ember Inspector, an extension for Google Chrome that exposes what happens with views, controllers, objects etc. when running an Ember.js application.
There’s already a few videos demonstrating the inspector, including Ember Inspector: Live Controllers. It will be officially available with the release of Ember.js version 1.0, but you can go ahead and try it out now. Here’s a quick guide:
  • Go to github.com/tildeio/ember-extension and download the ZIP file
  • Unzip the file and fire up Google Chrome
  • Visit chrome://flags and enable “Experimental Extension APIs” in the list
  • Restart Google Chrome
  • Go to the Extensions page and ensure that the “Developer Mode” checkbox is checked
  • Click “Load unpacked extension…” and select theember-extension-master folder
  • Restart Google Chrome and bring up the Developer Tools
  • Click “Ember” at the far right of the tab menu
That’s it. If all went okay, you should be seeing something like this in your Developer Tools menu. Happy inspecting!
(As a side note, in Google Chrome 24.x, it even had a nice, little icon.)

Update to ruby 2.0 with brew and Xcode

Uninstall XCode dev tools

-  sudo /Developer/Library/uninstall-devtools —mode=all

Removing empty devtools directories...
Finish time: Wed  5 Jun 2013 09:12:39 EST


get latest CL xCode from

https://developer.apple.com/downloads/index.action


Select Developer Tools

Search for "Command Line Tools" order by date get the latest one
i get "Command Line Tools (OS X Mountain Lion) for Xcode - April 2013"


check the gcc

- gcc --version

i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


IMPORTANT:
after installing CL tools close and open the teminal window (it take me 1 hour to solve this)

http://stackoverflow.com/questions/9323612/xcode-configure-error-no-acceptable-c-compiler-found-in-path


- ruby -v
ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-darwin11.1.0]


run:

- sudo brew update && brew doctor

-brew install libyaml
and make sure there are not errors


-rvm pkg install openssl

- rvm install 2.0.0 \
    --with-openssl-dir=$HOME/.rvm/usr \
    --verify-downloads 1

-rvm use 2.0.0


OR

- CC=clang rvm reinstall 2.0.0-p0


- sudo brew install git

------------------------------------------------------------------

Saving wrappers to '/Users/ioannis/.rvm/wrappers/ruby-2.0.0-p195'........

ruby-2.0.0-p195 - #adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
ruby-2.0.0-p195 - #importing default gemsets, this may take time.......................
Install of ruby-2.0.0-p195 - #complete


➜  Xcode  rvm use 2.0.0 --default
Using /Users/ioannis/.rvm/gems/ruby-2.0.0-p195
➜  Xcode  ruby -v
ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-darwin12.3.0]
➜  Xcode

:)








Monday, 3 June 2013

Node.js Frameworks Comparison! Which should i pick?





http://ocdevel.com/blog/nodejs-frameworks-comparison


select an MV* framework todo

Helping you select an MV* framework - Todo apps for Backbone.js, Ember.js, AngularJS, Spine and many more http://todomvc.com/

All node modules & web-frameworks

https://github.com/joyent/node/wiki/modules https://github.com/joyent/node/wiki/modules#wiki-web-frameworks

mongo db RegExp

var regex = new RegExp("^mongo(?:db)?://(?:|([^@/]*)@)([^@/]*)(?:|/([^?]*)(?:|\\?([^?]*)))$");
var match = process.env.MONGOHQ_URL.match(regex);
var auth = match[1].split(':', 2);
auth[0] = decodeURIComponent(auth[0]);
auth[1] = decodeURIComponent(auth[1]);
db.authenticate(auth[0], auth[1], function(err, success) {
if (err) {
console.error(err);
} else {
// worked >:O
}
});
//OR
var regex = new RegExp("^mongo(?:db)?://(?:|([^@/]*)@)([^@/]*)(?:|/([^?]*)(?:|\\?([^?]*)))$");
var con_url = "mongodb://heroku_app160846:2n2tlv5la7mi5sgpbhvj9j@ds027908.mongolab.com:27908/heroku_app161146";
var match = con_url.match(regex);
var auth = match[1].split(':', 2);
auth[0] = decodeURIComponent(auth[0]);
auth[1] = decodeURIComponent(auth[1]);
console.log(auth)
view raw mongo db RegExp hosted with ❤ by GitHub

MongoDb/Express/nodejs on heroku Blog example

##MongoDb Express nodejs and heroku Blog example

Clone my repo

git clone git@github.com:msroot/nodejs-express-mongo-example.git

Create local

sudo npm install express

sudo npm install express-messages

sudo npm install ejs

sudo npm install sass

sudo npm install mongoose

View the latestest from registry.npmjs.org

npm view <package-name> version

fixed your package.json

Update

sudo npm install -d npm list npm list --depth=0

###Deploy in heroku heroku create

heroku apps:rename your_app_name

heroku addons:add mongolab

heroku addons:open mongolab

git push heroku

heroku open

Run on localhost

node app.js

http://localhost:3000 visit: http://localhost:3000

Folked by: https://github.com/cmarin/MongoDB-Node-Express-Blog

Edited by:@yannis_kolovos

view raw gistfile1.md hosted with ❤ by GitHub
repo: https://github.com/msroot/nodejs-express-mongo-example

Sunday, 2 June 2013

Node.js express and mongodb

sudo npm install express -g 


  Development  cd Node_js_Express_MongoDB 
➜  Node_js_Express_MongoDB  ls
➜  Node_js_Express_MongoDB  express -c stylus


OR

express -c stylus YOUR_APP


   create : .
   create : ./package.json
   create : ./app.js
   create : ./public
   create : ./public/javascripts
   create : ./public/images
   create : ./public/stylesheets
   create : ./public/stylesheets/style.styl
   create : ./routes
   create : ./routes/index.js
   create : ./routes/user.js
   create : ./views
   create : ./views/layout.jade
   create : ./views/index.jade

   install dependencies:
     $ cd . && npm install

   run the app:
     $ node app

➜  Node_js_Express_MongoDB  npm install -d

jade@0.31.1 node_modules/jade
├── character-parser@1.0.2
├── mkdirp@0.3.5
├── commander@1.1.1 (keypress@0.1.0)
├── with@1.0.4 (lexical-scope@0.0.12)
├── monocle@0.1.48 (readdirp@0.2.4)
└── transformers@2.0.1 (promise@2.0.0, css@1.0.8, uglify-js@2.2.5)



Check id mondgo is running 

http://www.mkyong.com/mongodb/how-to-install-mongodb-on-mac-os-x/

Or install it here 

http://www.mkyong.com/mongodb/how-to-install-mongodb-on-mac-os-x/


Node_js_Express_MongoDB  ps -ef | grep mongo
    0    62     1   0 11May13 ??        67:51.38 /usr/local/mongodb/bin/mongod run --config /usr/local/mongodb/mongod.conf
    0 74879     1   0  7:21am ??         0:04.45 /usr/local/mongodb/bin/mongod
  501 75707 63231   0  7:36am ttys000    0:00.00 grep mongo



run the app 

node app.js


Express

Welcome to Express


:) 



require mongo 

in package.json 


{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.2.5",
    "jade": "*",
    "stylus": "*",
"mongodb": ">= 0.9.6-7"
  }
}


package.json  is like GEM file in rails


UPDATE 

npm install -d

Install nodemon
Nodemon will reload your application each time it changes so you don't need to restart it.
npm install -g nodemon

http://blog.ijasoneverett.com/2013/03/a-sample-app-with-node-js-express-and-mongodb-part-1/


http://expressjs.com/guide.html





UPDATE:

update the package.json because heroku need a version


{
  "name": "application-name",
  "version": "0.0.1",
"engines": {
       "node": "0.10.x",
       "npm":  "1.2.x"
   },
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.2.5",
    "jade": "*",
    "stylus": "*",
"mongodb": ">= 0.9.6-7"
  }
}






Push it on heroku

➜  Node_js_Express_MongoDB git:(master) ✗ heroku create                        
Creating nameless-sea-6255... done, stack is cedar
http://nameless-sea-6255.herokuapp.com/ | git@heroku.com:nameless-sea-6255.git
Git remote heroku added
➜  Node_js_Express_MongoDB git:(master) ✗ git push heroku 



add mongo to  heroku

heroku addons:add mongolab

➜  Node_js_Express_MongoDB git:(master)  heroku addons:add mongolab
----> Adding mongolab to nameless-sea-6255... done, v6 (free)

      Welcome to MongoLab.  Your new database is ready for use.  Please consult the MongoLab Add-on Admin UI for more information and useful management t


Create a Procfile

and add

web: node app.js
this tells heroku what to run when it deployed  


➜  Node_js_Express_MongoDB git:(master) heroku ps  
Process   State      Command
--------  ---------  -------
run.9003  up for 9m  node    
➜  Node_js_Express_MongoDB git:(master) heroku ps:scale web=1
Scaling web processes... done, now running 1
➜  Node_js_Express_MongoDB git:(master) heroku config:add NODE_ENV=production
Adding config vars and restarting app... done, v8
  NODE_ENV => production


Change on app.js


var port = process.env.PORT || 3000;

app.listen(port);

https://devcenter.heroku.com/articles/nodejs-mongoose


Heroku connection string

https://github.com/p15martin/BlogMongoDbNativeDriver/blob/master/web.js


heroku config | grep MONGOLAB_URI




update node js

sudo npm cache clean -f
sudo npm install -g n
sudo n stable
sudo n
node -v
view raw update node hosted with ❤ by GitHub