SlideShare a Scribd company logo
1 of 32
Download to read offline
CONVERTING TO NODE
How I converted a medium sized Rails project to Node.js
BACKGROUND
•

CTO of Ideal Candidate	


•

MVP existed when I joined	


•

Author of Haraka and a few
other Node.js libraries	


•

Background in Perl and
Anti-Spam
THE RAILS APP
•

Unicorn + Thin + Rails	


•

CoffeeScript with Angular.JS	


•

SASS+Compass for stylesheets	


•

HAML for templates	


•

MySQL + MongoDB	


•

Sidekiq for background tasks
WHY?
APP SIZE
•

5700 Lines of Ruby (170 files)	


•

2500 Lines of CoffeeScript (119 files)	


•

3800 Lines of SASS (42 files)	


•

1500 Lines of HAML (100 files)
FINAL GOAL
•

Express + minimal middleware	


•

PostgreSQL hand coded with referential integrity	


•

Jade templates	


•

SCSS for CSS	


•

Javascript + Angular.js frontend
HOW?
It’s all about the information, Marty
RAILS GIVES YOU
•

Routes	


•

Middleware	


•

DB abstraction layer (aka Model)	


•

Views	


•

Controllers	


•

Configuration	


•

Plugins	


•

A directory structure	


•

Unit tests
EXPRESS GIVES YOU
•

Routes	


•

Middleware	


•

That’s it	


•

(This scares a lot of people)
DIRECTORY STRUCTURE
lib
- general JS libraries	

⌞ model - database accessors	

public
- files that get served to the front end	

⌞ assets - files that are considered part of the app	

⌞ javascripts	

⌞ stylesheets	

⌞ images	

routes
- files that provide express routes for HTML	

⌞ api/v1 - files providing REST API endpoints (JSON)	

views
- Jade templates	

app.js
- entry point
RAILS ASSET PIPELINE
•

Rails does a lot for you, but it’s f ’ing confusing	


•

HAML Template Example:	

•

= javascript_include_tag :application	


•

You’d think this adds <script
src=“application.js”>, but no.
RAILS ASSET PIPELINE
•

Easy if you understand it	


•

Too much magic for my liking	


•

But… the overall effect is good. So I copied some
of it.
JADE EQUIVALENT
	

	

each script in javascripts	
script(src=script, type=“text/javascript”)
APP.JS:
var js = find.fileSync(/.(coffee|js)$/, __dirname + 	
	 ‘/public/assets/javascripts/controllers')	
	 .map(function (i) {	
	 	 return i.replace(/^.*/assets/, ‘/assets')	
	 	 	 	 .replace(/.coffee$/, ‘.js')	
	 });	
app.all('*', function (req, res, next) {	
res.locals.javascripts = js;	
next();	
});
SERVING COFFEESCRIPT
// development	
app.use(require('coffee-middleware')({	
src: __dirname + '/public',	
compress: false,	
}));	

!

// Production	
var all_js = coffee_compiler.generate(js, true);	

!

var shasum = crypto.createHash('sha256');	
shasum.update(all_js);	
var js_sha = shasum.digest('hex');	

!

js = ['/assets/javascripts/application-' + js_sha + '.js'];	

!

app.get('/assets/javascripts/application-' + js_sha + '.js', function (req, res) {	
res.type('js');	
res.setHeader('Cache-Control', 'public, max-age=31557600');	
res.end(all_js);	
});
SERVING SCSS
•

Node-sass module serves .scss files	


•

Doesn’t serve up .sass files (weird, huh?)	


!
# mass-convert.bash	
for F in `find . -name *.sass`; do	
O=“${F/.sass/.scss}”	
sass-convert -F sass -T scss “$F” “$O”	
git rm -f “$F”	
git add “$O”	
done
SCSS APP.JS
function compile_css () {	
console.log("Recompiling CSS");	
resources.watchers.forEach(function (w) {	
w.close();	
});	
	
resources.watchers = [];	

!

!
!
!
}

resources.css = sass.renderSync({	
file: __dirname + '/public/assets/stylesheets/application.scss',	
includePaths: [__dirname + '/public/assets/stylesheets'],	
});	
var shasum = crypto.createHash('sha256');	
shasum.update(resources.css);	
var css_sha = shasum.digest('hex');	
resources.stylesheets[0] = '/assets/stylesheets/application-' + css_sha + '.css';	
resources.stylesheets[1] = '//fonts.googleapis.com/css?family=Open+Sans:400,700,800,300,600';	
find.fileSync(cssregexp, __dirname + '/public/assets/stylesheets').forEach(function (f) {	
resources.watchers.push(fs.watch(f, compile_css));	
})
SCSS APP.JS

compile_css();	

!
// Dev and Production the same	
app.get(//assets/stylesheets/application-(w+).css/, function (req, res) {	
res.type('css');	
res.setHeader('Cache-Control', 'public, max-age=31557600');	
res.end(resources.css);	
});
ADDING COMPASS
•

Ruby CSS framework	


•

Luckily only the CSS3 part used	


•

CSS3 code is just SASS files	


•

Once I figured this out, copied them into my
project, et voila!
CONVERTING HAML TO JADE
•

Both indent based	


•

HAML:	


	
	
	
	
	

•
	
	
	

•

	
	
	
	
	

%tag{attr: “Value”}	
	
Some Text	
.person	
	
.name	
	
	
Bob	

JADE:	

	
	
	

tag(attr=“Value”) Some Text	
.person	
	
.name Bob	

Other subtle differences too
CONVERSION TOOL: SUBLIME
TEXT
•

Afterthought: I should have written something in Perl	


•

Regexp Find/Replace	

•

^(s*)%

=> $1 (fix tags)	


•

(w){(.*)} => $1($2) (attribute curlys)	


•

(w):s*([“‘]) => $1=$2 (attribute key: value)
THINGS LEFT TO FIX
•

Helpers: = some_helper	


•

Text on a line on its own - Jade treats these as tags	


•

Nested attributes:	


	
	

•

	
->

%tag{ng:{style:’…’,click:’…’},class:’foo’}	
tag(ng-style=‘…’, ng-click=‘…’, class=‘foo’)	

Making sure the output matched the Ruby/HAML
version was HARD - HTML Diff tools suck
HELPERS BECAME MIXINS
•

Standard Rails Helpers:	


= form_for @person do |f|	
f.label :first_name	
f.text_field :first_name	
%br	

!
f.label :last_name	
f.text_field :last_name	
%br	

!
f.submit	

•

Custom Rails helpers stored in app/helpers/ folder	


•

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
JADE MIXINS
•

Very powerful. Poorly documented.	


•

Standalone or can have block contents	

// implementation	
mixin form(action)	
form(accept-charset="UTF-8", action=action, method="POST")	
input(name="utf8" type="hidden" value="&#x2713;")	
block	
// usage:	
+form(‘/post/to/here’)	
input(type=“text”,name=“hello”,value=“world”)	

•

Supports js code	

mixin app_error(field)	
if (errors && errors[field])	
div(class="err_msg " + field)	
each error in errors[field]	
span= error
JADE: NO DYNAMIC
INCLUDES
•

HAML/Helpers can do:	


	 	

= popup ‘roles/new'	

•

Jade needed:	


	
	

	
	

+popup(‘roles/new’)	
	
include ../roles/new
CREATING THE MODEL
•

Hand coded db.js layer developed over time from previous
projects	


•

One file per table (generally) in lib/model/*.js	


	
	
	
	
	

"use strict";	
	
var db = require('./db');	
	
exports.get = function get (id, cb) {	
	
	
db.get_one_row("SELECT * FROM Answers WHERE id=$1", [id], cb);	
}	
	
exports.get_by_submission_id = function (submission_id, cb) {	
	
	
db.query("SELECT * FROM Answers	
	
WHERE submission_id=$1	
	
	
ORDER BY question_id", [submission_id], cb);	
}
WHY CONTROL THE SQL?
exports.get_avg_team_size = function (company_id, role_id, months, cb) {	
var role_sql = role_id ? ' AND role_id=$2' : ' AND $2=$2';	

!
!

}	

if (months == 0 || months == '0') {	
months = '9000'; // OVER NINE THOUSAND	
}	
var sql = "SELECT avg(c) as value	
FROM (	
SELECT g.month, count(e.*)	
FROM generate_series(	
date_trunc('month', now() - CAST($3 AS INTERVAL)),	
now(),	
INTERVAL '1 month') g(month)	
LEFT JOIN employees e ON e.company_id=$1" + role_sql + "	
AND (start_date, COALESCE(end_date, 'infinity'))	
OVERLAPS	
(g.month, INTERVAL '1 month')	
GROUP BY g.month	
HAVING count(e.*) > 0	
) av(month,c)";	
db.get_one_row(sql, [company_id, role_id, months + " months"], cb);
AND FINALLY…
•

Routes	

•

Run Rails version of App	


•

Open Chrome Dev Console Network tools	


•

Hit record	


•

Find all routes and implement them
CREATING ROUTES/MODELS
•

While I glossed over this, it was the bulk of the
work	


•

Each endpoint was painstakingly re-created	


•

This allowed me to get a view of the DB layout	

•

And fix design bugs in the DB layout

find.fileSync(/.js$/, __dirname + '/routes').forEach(function (route_file) {	
require(route_file);	
});
BACKGROUND TASKS
•

Currently using Sidekiq, which uses Redis as a queue	

•

Used for downloading slow data feeds	


•

Node.js doesn’t care if downloads are slow	


•

So I punted on background tasks for now	


•

If I need them later I will use Kue (see npmjs.org)
DEPLOYMENT
•

Linode + Nginx + Postgres 9.3.1 + Runit +
Memcached	


•

/var/apps and deploy_to_runit for github autodeploy	


•

Monitoring via Zabbix	


•

60M used vs 130M for Rails
NEXT STEPS
•

Convert coffeescript code to plain JS - I find
coffeescript too much of a pain	


•

Implement graceful restarts using cluster	


•

Consider porting CSS to Bootstrap so we get
mobile support

More Related Content

What's hot

Containerised Bioinformatics Pipeline on AWS
Containerised Bioinformatics Pipeline on AWSContainerised Bioinformatics Pipeline on AWS
Containerised Bioinformatics Pipeline on AWSAmazon Web Services
 
Chapter 15 software product metrics
Chapter 15 software product metricsChapter 15 software product metrics
Chapter 15 software product metricsSHREEHARI WADAWADAGI
 
MLOps - The Assembly Line of ML
MLOps - The Assembly Line of MLMLOps - The Assembly Line of ML
MLOps - The Assembly Line of MLJordan Birdsell
 
Capability Maturity Model
Capability Maturity ModelCapability Maturity Model
Capability Maturity ModelUzair Akram
 
Lecture 9 understanding requirements
Lecture 9   understanding requirementsLecture 9   understanding requirements
Lecture 9 understanding requirementsIIUI
 
MLOps and Data Quality: Deploying Reliable ML Models in Production
MLOps and Data Quality: Deploying Reliable ML Models in ProductionMLOps and Data Quality: Deploying Reliable ML Models in Production
MLOps and Data Quality: Deploying Reliable ML Models in ProductionProvectus
 
Drifting Away: Testing ML Models in Production
Drifting Away: Testing ML Models in ProductionDrifting Away: Testing ML Models in Production
Drifting Away: Testing ML Models in ProductionDatabricks
 
Seamless MLOps with Seldon and MLflow
Seamless MLOps with Seldon and MLflowSeamless MLOps with Seldon and MLflow
Seamless MLOps with Seldon and MLflowDatabricks
 
Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...Neo4j
 
Graph Algorithms for Developers
Graph Algorithms for DevelopersGraph Algorithms for Developers
Graph Algorithms for DevelopersNeo4j
 
ML-Ops: From Proof-of-Concept to Production Application
ML-Ops: From Proof-of-Concept to Production ApplicationML-Ops: From Proof-of-Concept to Production Application
ML-Ops: From Proof-of-Concept to Production ApplicationHunter Carlisle
 
CI/CD Templates: Continuous Delivery of ML-Enabled Data Pipelines on Databricks
CI/CD Templates: Continuous Delivery of ML-Enabled Data Pipelines on DatabricksCI/CD Templates: Continuous Delivery of ML-Enabled Data Pipelines on Databricks
CI/CD Templates: Continuous Delivery of ML-Enabled Data Pipelines on DatabricksDatabricks
 
Chapter 1 - Software Design - Introduction.pptx
Chapter 1 - Software Design - Introduction.pptxChapter 1 - Software Design - Introduction.pptx
Chapter 1 - Software Design - Introduction.pptxHaifaMohd3
 
ML-Ops how to bring your data science to production
ML-Ops  how to bring your data science to productionML-Ops  how to bring your data science to production
ML-Ops how to bring your data science to productionHerman Wu
 
Software Configuration Management (SCM)
Software Configuration Management (SCM)Software Configuration Management (SCM)
Software Configuration Management (SCM)Nishkarsh Gupta
 
Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Paulo Gandra de Sousa
 
Modelling Microservices at Spotify - Petter Mahlen
Modelling Microservices at Spotify - Petter MahlenModelling Microservices at Spotify - Petter Mahlen
Modelling Microservices at Spotify - Petter MahlenJ On The Beach
 
MLOps Using MLflow
MLOps Using MLflowMLOps Using MLflow
MLOps Using MLflowDatabricks
 

What's hot (20)

Containerised Bioinformatics Pipeline on AWS
Containerised Bioinformatics Pipeline on AWSContainerised Bioinformatics Pipeline on AWS
Containerised Bioinformatics Pipeline on AWS
 
Chapter 15 software product metrics
Chapter 15 software product metricsChapter 15 software product metrics
Chapter 15 software product metrics
 
MLOps - The Assembly Line of ML
MLOps - The Assembly Line of MLMLOps - The Assembly Line of ML
MLOps - The Assembly Line of ML
 
Capability Maturity Model
Capability Maturity ModelCapability Maturity Model
Capability Maturity Model
 
Lecture 9 understanding requirements
Lecture 9   understanding requirementsLecture 9   understanding requirements
Lecture 9 understanding requirements
 
MLOps and Data Quality: Deploying Reliable ML Models in Production
MLOps and Data Quality: Deploying Reliable ML Models in ProductionMLOps and Data Quality: Deploying Reliable ML Models in Production
MLOps and Data Quality: Deploying Reliable ML Models in Production
 
Drifting Away: Testing ML Models in Production
Drifting Away: Testing ML Models in ProductionDrifting Away: Testing ML Models in Production
Drifting Away: Testing ML Models in Production
 
MLOps in action
MLOps in actionMLOps in action
MLOps in action
 
Seamless MLOps with Seldon and MLflow
Seamless MLOps with Seldon and MLflowSeamless MLOps with Seldon and MLflow
Seamless MLOps with Seldon and MLflow
 
Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...Designing and Building a Graph Database Application – Architectural Choices, ...
Designing and Building a Graph Database Application – Architectural Choices, ...
 
Graph Algorithms for Developers
Graph Algorithms for DevelopersGraph Algorithms for Developers
Graph Algorithms for Developers
 
ML-Ops: From Proof-of-Concept to Production Application
ML-Ops: From Proof-of-Concept to Production ApplicationML-Ops: From Proof-of-Concept to Production Application
ML-Ops: From Proof-of-Concept to Production Application
 
CI/CD Templates: Continuous Delivery of ML-Enabled Data Pipelines on Databricks
CI/CD Templates: Continuous Delivery of ML-Enabled Data Pipelines on DatabricksCI/CD Templates: Continuous Delivery of ML-Enabled Data Pipelines on Databricks
CI/CD Templates: Continuous Delivery of ML-Enabled Data Pipelines on Databricks
 
Chapter 1 - Software Design - Introduction.pptx
Chapter 1 - Software Design - Introduction.pptxChapter 1 - Software Design - Introduction.pptx
Chapter 1 - Software Design - Introduction.pptx
 
ML-Ops how to bring your data science to production
ML-Ops  how to bring your data science to productionML-Ops  how to bring your data science to production
ML-Ops how to bring your data science to production
 
Software Configuration Management (SCM)
Software Configuration Management (SCM)Software Configuration Management (SCM)
Software Configuration Management (SCM)
 
Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)
 
Web Application Security Strategy
Web Application Security Strategy Web Application Security Strategy
Web Application Security Strategy
 
Modelling Microservices at Spotify - Petter Mahlen
Modelling Microservices at Spotify - Petter MahlenModelling Microservices at Spotify - Petter Mahlen
Modelling Microservices at Spotify - Petter Mahlen
 
MLOps Using MLflow
MLOps Using MLflowMLOps Using MLflow
MLOps Using MLflow
 

Similar to Converting a Rails application to Node.js

Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneMarius Soutier
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Ayes Chinmay
 
前端MVC之BackboneJS
前端MVC之BackboneJS前端MVC之BackboneJS
前端MVC之BackboneJSZhang Xiaoxue
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Amazon Web Services for PHP Developers
Amazon Web Services for PHP DevelopersAmazon Web Services for PHP Developers
Amazon Web Services for PHP DevelopersJeremy Lindblom
 
(BDT401) Big Data Orchestra - Harmony within Data Analysis Tools | AWS re:Inv...
(BDT401) Big Data Orchestra - Harmony within Data Analysis Tools | AWS re:Inv...(BDT401) Big Data Orchestra - Harmony within Data Analysis Tools | AWS re:Inv...
(BDT401) Big Data Orchestra - Harmony within Data Analysis Tools | AWS re:Inv...Amazon Web Services
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache KafkaSolutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache KafkaGuido Schmutz
 
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...confluent
 
3 Dundee-Spark Overview for C* developers
3 Dundee-Spark Overview for C* developers3 Dundee-Spark Overview for C* developers
3 Dundee-Spark Overview for C* developersChristopher Batey
 
Manchester Hadoop Meetup: Spark Cassandra Integration
Manchester Hadoop Meetup: Spark Cassandra IntegrationManchester Hadoop Meetup: Spark Cassandra Integration
Manchester Hadoop Meetup: Spark Cassandra IntegrationChristopher Batey
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Matthew Groves
 
Full Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQLFull Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQLAll Things Open
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQLjeykottalam
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaKazuhiro Sera
 
Reading Cassandra Meetup Feb 2015: Apache Spark
Reading Cassandra Meetup Feb 2015: Apache SparkReading Cassandra Meetup Feb 2015: Apache Spark
Reading Cassandra Meetup Feb 2015: Apache SparkChristopher Batey
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 

Similar to Converting a Rails application to Node.js (20)

Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG Cologne
 
Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
 
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-10) [Node.js] | NIC/NIELIT Web Technology
 
前端MVC之BackboneJS
前端MVC之BackboneJS前端MVC之BackboneJS
前端MVC之BackboneJS
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Amazon Web Services for PHP Developers
Amazon Web Services for PHP DevelopersAmazon Web Services for PHP Developers
Amazon Web Services for PHP Developers
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
(BDT401) Big Data Orchestra - Harmony within Data Analysis Tools | AWS re:Inv...
(BDT401) Big Data Orchestra - Harmony within Data Analysis Tools | AWS re:Inv...(BDT401) Big Data Orchestra - Harmony within Data Analysis Tools | AWS re:Inv...
(BDT401) Big Data Orchestra - Harmony within Data Analysis Tools | AWS re:Inv...
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache KafkaSolutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
Solutions for bi-directional Integration between Oracle RDMBS & Apache Kafka
 
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
Solutions for bi-directional integration between Oracle RDBMS and Apache Kafk...
 
3 Dundee-Spark Overview for C* developers
3 Dundee-Spark Overview for C* developers3 Dundee-Spark Overview for C* developers
3 Dundee-Spark Overview for C* developers
 
Manchester Hadoop Meetup: Spark Cassandra Integration
Manchester Hadoop Meetup: Spark Cassandra IntegrationManchester Hadoop Meetup: Spark Cassandra Integration
Manchester Hadoop Meetup: Spark Cassandra Integration
 
Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017Full stack development with node and NoSQL - All Things Open - October 2017
Full stack development with node and NoSQL - All Things Open - October 2017
 
Full Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQLFull Stack Development with Node.js and NoSQL
Full Stack Development with Node.js and NoSQL
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
Reading Cassandra Meetup Feb 2015: Apache Spark
Reading Cassandra Meetup Feb 2015: Apache SparkReading Cassandra Meetup Feb 2015: Apache Spark
Reading Cassandra Meetup Feb 2015: Apache Spark
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 

Recently uploaded

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Recently uploaded (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

Converting a Rails application to Node.js

  • 1. CONVERTING TO NODE How I converted a medium sized Rails project to Node.js
  • 2. BACKGROUND • CTO of Ideal Candidate • MVP existed when I joined • Author of Haraka and a few other Node.js libraries • Background in Perl and Anti-Spam
  • 3. THE RAILS APP • Unicorn + Thin + Rails • CoffeeScript with Angular.JS • SASS+Compass for stylesheets • HAML for templates • MySQL + MongoDB • Sidekiq for background tasks
  • 5. APP SIZE • 5700 Lines of Ruby (170 files) • 2500 Lines of CoffeeScript (119 files) • 3800 Lines of SASS (42 files) • 1500 Lines of HAML (100 files)
  • 6. FINAL GOAL • Express + minimal middleware • PostgreSQL hand coded with referential integrity • Jade templates • SCSS for CSS • Javascript + Angular.js frontend
  • 7. HOW? It’s all about the information, Marty
  • 8. RAILS GIVES YOU • Routes • Middleware • DB abstraction layer (aka Model) • Views • Controllers • Configuration • Plugins • A directory structure • Unit tests
  • 9. EXPRESS GIVES YOU • Routes • Middleware • That’s it • (This scares a lot of people)
  • 10. DIRECTORY STRUCTURE lib - general JS libraries ⌞ model - database accessors public - files that get served to the front end ⌞ assets - files that are considered part of the app ⌞ javascripts ⌞ stylesheets ⌞ images routes - files that provide express routes for HTML ⌞ api/v1 - files providing REST API endpoints (JSON) views - Jade templates app.js - entry point
  • 11. RAILS ASSET PIPELINE • Rails does a lot for you, but it’s f ’ing confusing • HAML Template Example: • = javascript_include_tag :application • You’d think this adds <script src=“application.js”>, but no.
  • 12. RAILS ASSET PIPELINE • Easy if you understand it • Too much magic for my liking • But… the overall effect is good. So I copied some of it.
  • 13. JADE EQUIVALENT each script in javascripts script(src=script, type=“text/javascript”)
  • 14. APP.JS: var js = find.fileSync(/.(coffee|js)$/, __dirname + ‘/public/assets/javascripts/controllers') .map(function (i) { return i.replace(/^.*/assets/, ‘/assets') .replace(/.coffee$/, ‘.js') }); app.all('*', function (req, res, next) { res.locals.javascripts = js; next(); });
  • 15. SERVING COFFEESCRIPT // development app.use(require('coffee-middleware')({ src: __dirname + '/public', compress: false, })); ! // Production var all_js = coffee_compiler.generate(js, true); ! var shasum = crypto.createHash('sha256'); shasum.update(all_js); var js_sha = shasum.digest('hex'); ! js = ['/assets/javascripts/application-' + js_sha + '.js']; ! app.get('/assets/javascripts/application-' + js_sha + '.js', function (req, res) { res.type('js'); res.setHeader('Cache-Control', 'public, max-age=31557600'); res.end(all_js); });
  • 16. SERVING SCSS • Node-sass module serves .scss files • Doesn’t serve up .sass files (weird, huh?) ! # mass-convert.bash for F in `find . -name *.sass`; do O=“${F/.sass/.scss}” sass-convert -F sass -T scss “$F” “$O” git rm -f “$F” git add “$O” done
  • 17. SCSS APP.JS function compile_css () { console.log("Recompiling CSS"); resources.watchers.forEach(function (w) { w.close(); }); resources.watchers = []; ! ! ! ! } resources.css = sass.renderSync({ file: __dirname + '/public/assets/stylesheets/application.scss', includePaths: [__dirname + '/public/assets/stylesheets'], }); var shasum = crypto.createHash('sha256'); shasum.update(resources.css); var css_sha = shasum.digest('hex'); resources.stylesheets[0] = '/assets/stylesheets/application-' + css_sha + '.css'; resources.stylesheets[1] = '//fonts.googleapis.com/css?family=Open+Sans:400,700,800,300,600'; find.fileSync(cssregexp, __dirname + '/public/assets/stylesheets').forEach(function (f) { resources.watchers.push(fs.watch(f, compile_css)); })
  • 18. SCSS APP.JS compile_css(); ! // Dev and Production the same app.get(//assets/stylesheets/application-(w+).css/, function (req, res) { res.type('css'); res.setHeader('Cache-Control', 'public, max-age=31557600'); res.end(resources.css); });
  • 19. ADDING COMPASS • Ruby CSS framework • Luckily only the CSS3 part used • CSS3 code is just SASS files • Once I figured this out, copied them into my project, et voila!
  • 20. CONVERTING HAML TO JADE • Both indent based • HAML: • • %tag{attr: “Value”} Some Text .person .name Bob JADE: tag(attr=“Value”) Some Text .person .name Bob Other subtle differences too
  • 21. CONVERSION TOOL: SUBLIME TEXT • Afterthought: I should have written something in Perl • Regexp Find/Replace • ^(s*)% => $1 (fix tags) • (w){(.*)} => $1($2) (attribute curlys) • (w):s*([“‘]) => $1=$2 (attribute key: value)
  • 22. THINGS LEFT TO FIX • Helpers: = some_helper • Text on a line on its own - Jade treats these as tags • Nested attributes: • -> %tag{ng:{style:’…’,click:’…’},class:’foo’} tag(ng-style=‘…’, ng-click=‘…’, class=‘foo’) Making sure the output matched the Ruby/HAML version was HARD - HTML Diff tools suck
  • 23. HELPERS BECAME MIXINS • Standard Rails Helpers: = form_for @person do |f| f.label :first_name f.text_field :first_name %br ! f.label :last_name f.text_field :last_name %br ! f.submit • Custom Rails helpers stored in app/helpers/ folder • http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html
  • 24. JADE MIXINS • Very powerful. Poorly documented. • Standalone or can have block contents // implementation mixin form(action) form(accept-charset="UTF-8", action=action, method="POST") input(name="utf8" type="hidden" value="&#x2713;") block // usage: +form(‘/post/to/here’) input(type=“text”,name=“hello”,value=“world”) • Supports js code mixin app_error(field) if (errors && errors[field]) div(class="err_msg " + field) each error in errors[field] span= error
  • 25. JADE: NO DYNAMIC INCLUDES • HAML/Helpers can do: = popup ‘roles/new' • Jade needed: +popup(‘roles/new’) include ../roles/new
  • 26. CREATING THE MODEL • Hand coded db.js layer developed over time from previous projects • One file per table (generally) in lib/model/*.js "use strict"; var db = require('./db'); exports.get = function get (id, cb) { db.get_one_row("SELECT * FROM Answers WHERE id=$1", [id], cb); } exports.get_by_submission_id = function (submission_id, cb) { db.query("SELECT * FROM Answers WHERE submission_id=$1 ORDER BY question_id", [submission_id], cb); }
  • 27. WHY CONTROL THE SQL? exports.get_avg_team_size = function (company_id, role_id, months, cb) { var role_sql = role_id ? ' AND role_id=$2' : ' AND $2=$2'; ! ! } if (months == 0 || months == '0') { months = '9000'; // OVER NINE THOUSAND } var sql = "SELECT avg(c) as value FROM ( SELECT g.month, count(e.*) FROM generate_series( date_trunc('month', now() - CAST($3 AS INTERVAL)), now(), INTERVAL '1 month') g(month) LEFT JOIN employees e ON e.company_id=$1" + role_sql + " AND (start_date, COALESCE(end_date, 'infinity')) OVERLAPS (g.month, INTERVAL '1 month') GROUP BY g.month HAVING count(e.*) > 0 ) av(month,c)"; db.get_one_row(sql, [company_id, role_id, months + " months"], cb);
  • 28. AND FINALLY… • Routes • Run Rails version of App • Open Chrome Dev Console Network tools • Hit record • Find all routes and implement them
  • 29. CREATING ROUTES/MODELS • While I glossed over this, it was the bulk of the work • Each endpoint was painstakingly re-created • This allowed me to get a view of the DB layout • And fix design bugs in the DB layout find.fileSync(/.js$/, __dirname + '/routes').forEach(function (route_file) { require(route_file); });
  • 30. BACKGROUND TASKS • Currently using Sidekiq, which uses Redis as a queue • Used for downloading slow data feeds • Node.js doesn’t care if downloads are slow • So I punted on background tasks for now • If I need them later I will use Kue (see npmjs.org)
  • 31. DEPLOYMENT • Linode + Nginx + Postgres 9.3.1 + Runit + Memcached • /var/apps and deploy_to_runit for github autodeploy • Monitoring via Zabbix • 60M used vs 130M for Rails
  • 32. NEXT STEPS • Convert coffeescript code to plain JS - I find coffeescript too much of a pain • Implement graceful restarts using cluster • Consider porting CSS to Bootstrap so we get mobile support

Editor's Notes

  1. Knowledge Hiring Lack of “Magic” Performance Queryability PostgreSQL Referential integrity Pre-Customers so zero downtime
  2. “Little ones and zeros, it’s all just electrons”. Web apps are a flow of information. HTML+JS goes to the client, XHR queries come back, XHR responses get sent, POST and PUT requests modify data. Monitor all these, watch the flow, and you have your app. The backend is unimportant at that level.
  3. And probably more
  4. Let’s start with a solid directory structure. I always do this when I’m creating express apps as it helps me stay grounded and not create too many hacks. My app.js has evolved a bit over time to include many things. Happy to share it.
  5. What it actually does: Looks for your application.js. If it doesn’t find it, looks for application.coffee. It then scans that file for comments containing =require or =require_tree In production it loads all those files, coffee script compiles them if necessary, minimises, and delivers via a &lt;script src=“application-$md5.js”&gt;. In dev, it puts in as many &lt;script&gt; tags as required for each file and delivers them, coffee script compiled. Rails does the same for SASS stylesheets. FML.
  6. I wrote coffee_compiler - but it’s very simple
  7. Did this by installing the gem, finding the .sass files, and copying them over to my project.
  8. Helpers are functions to simplify HTML generation. Rails comes with a bunch that help with creating forms (and some others). These had to be ported to become Jade mixins.
  9. HAML version creates some HTML and loads the template ‘views/roles/new’ to be part of the content Jade cannot do that, so we manually include the template
  10. Slightly more code than ActiveRecord, but gives you full control over SQL Only returns plain objects, doesn’t support dynamic updates Considering using getters/setters for next iteration, but not sure how they serialize