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

Thursday 13 June 2013

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

AngularJS_generator




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

:)








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