Many people understand the very basics of several languages, all the way to Hello World. However, this isn’t a full fledged application and it’s challenging to make the translations in your head between all the different dialects (interpreted languages aren’t really different from each other like different languages – they work very much the same and the only difference is in the structure of the language). Out in our community are many people who firmly believe that moving from Ruby to Perl is not possible, that it’s very difficult to learn a new language, that it makes no sense to try to understand what “foreign” code might be doing.
In this talk I will cover the example in 5 different languages (Perl, Ruby, PHP, Python, Node) and show how to map the exact same functionality to different languages.
The code can be found on Github at http://www.github.com/synedra/polyglot
19. Kirsten Hunter
@synedra
http://www.princesspolymath.com
Perl - Mongo Setupuse Dancer;
use Dancer::Plugin::CRUD;
use MongoDB;
my $client = MongoDB->connect();
my $db = $client->get_database('test');
my $quotes = $db->get_collection('quotes');
my $json = JSON->new->allow_nonref;
set content_type => 'application/json';
get '/' => sub{
return {message => "Hello from Perl and Dancer"};
};
set public => path(dirname(__FILE__), '..', 'static');
get "/demo/?" => sub {
send_file '/index.html'
};
get '/api/quotes' => sub {
my $response = $quotes->find()->sort({'index' => -1})->limit(10);
my @results = ();
while(my $quote = $response->next) {
push (@results,
20. Kirsten Hunter
@synedra
http://www.princesspolymath.com
Perl - Static Files
use Dancer;
use Dancer::Plugin::CRUD;
use MongoDB;
my $client = MongoDB->connect();
my $db = $client->get_database('test');
my $quotes = $db->get_collection('quotes');
my $json = JSON->new->allow_nonref;
set content_type => 'application/json';
get '/' => sub{
return {message => "Hello from Perl and Dancer"};
};
set public => path(dirname(__FILE__), '..', 'static');
get "/demo/?" => sub {
send_file '/index.html'
};
get '/api/quotes' => sub {
my $response = $quotes->find()->sort({'index' => -1})->limit(10);
my @results = ();
while(my $quote = $response->next) {
push (@results,
21. Kirsten Hunter
@synedra
http://www.princesspolymath.com
Perl - Routes
get '/api/quotes' => sub {
my $response = $quotes->find()->sort({'index' => -1})->limit(10);
my @results = ();
while(my $quote = $response->next) {
push (@results,
{"content" => $quote->{'content'},
"index" => $quote->{'index'},
"author" => $quote->{'author'}
}
);
}
if (! scalar (@results)) {
status 404;
return;
}
return @results;
};
24. Kirsten Hunter
@synedra
http://www.princesspolymath.com
Python - Route
# shows a list of all quotes, and lets you POST to add new quotes
class QuoteList(Resource):
def get(self):
quotes = mongo.db.quotes.find().sort("index", -1).limit(10)
resp = Response(dumps(quotes, default=default),
mimetype='application/json')
return resp
def post(self):
args = parser.parse_args()
quotes = mongo.db.quotes.find().sort("index", -1).limit(1)
print quotes[0]
args["index"] = int(quotes[0]["index"]) + 1
print args
try:
mongo.db.quotes.insert(args)
except Error as ve:
abort(400, str(ve))
return 201
api.add_resource(QuoteList, '/api/quotes')
api.add_resource(Quote, '/api/quotes/<quote_id>')
25. Kirsten Hunter
@synedra
http://www.princesspolymath.com
Ruby - Mongo Setup
class Quote
include Mongoid::Document
field :index
field :author
field :content
end
Mongoid.load!("mongoid.yml", :development)
set :port, 3000
set :bind, '0.0.0.0'
get '/demo*' do
content_type :html
File.read(File.join('../static', 'index.html'))
end
get '/' do
content_type :html
"Hello World from Sinatra"
end
before do
content_type 'application/json'
end
26. Kirsten Hunter
@synedra
http://www.princesspolymath.com
class Quote
include Mongoid::Document
field :index
field :author
field :content
end
Mongoid.load!("mongoid.yml", :development)
set :port, 3000
set :bind, '0.0.0.0'
get '/demo*' do
content_type :html
File.read(File.join('../static', 'index.html'))
end
get '/' do
content_type :html
"Hello World from Sinatra"
end
before do
content_type 'application/json'
end
Ruby - Static
27. Kirsten Hunter
@synedra
http://www.princesspolymath.com
before do
content_type 'application/json'
end
namespace "/api" do
# list all
get '/quotes' do
Quote.all.desc(:index).limit(10).to_json
end
get '/quotes/random' do
newnumber = Quote.count
random_num = rand(newnumber)
quote = Quote.find_by(index: random_num.to_i)
return status 404 if quote.nil?
quote.to_json
end
# view one
get '/quotes/:index' do
quote = Quote.find_by(index: params[:index].to_i)
return status 404 if quote.nil?
quote.to_json
end
Ruby - Route
28. Kirsten Hunter
@synedra
http://www.princesspolymath.com
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
var quoteSchema = mongoose.Schema({
content: String,
author: String,
index: Number
});
var Quote = mongoose.model('Quote', quoteSchema)
Quote.count().exec(function(err, count){
quotecount = count;
});
var express = require('express');
var app = express();
var router = express.Router();
var path = require('path');
var bodyParser = require('body-parser');
app.use('/demo', express.static(path.join(__dirname, '..', 'static')));
app.use(bodyParser.json());
// index
Node - Mongo Setup
29. Kirsten Hunter
@synedra
http://www.princesspolymath.com
var express = require('express');
var app = express();
var router = express.Router();
var path = require('path');
var bodyParser = require('body-parser');
app.use('/demo', express.static(path.join(__dirname, '..', 'static')));
app.use(bodyParser.json());
// index
app.get('/', function(req, res) {
res.send('Hello world from express');
});
app.use('/api', router);
// REST API
router.route('/quotes/random')
.get(function(req, res, next) {
var random = Math.floor(Math.random() * quotecount);
Quote.findOne({"index":random},
function (err, result) {
if (err) {
console.log(err);
res.redirect('/quotes/random');
}
res.send(result);
Node - Express Static
30. Kirsten Hunter
@synedra
http://www.princesspolymath.com
var express = require('express');
var app = express();
var router = express.Router();
var path = require('path');
var bodyParser = require('body-parser');
app.use('/demo', express.static(path.join(__dirname, '..', 'static')));
app.use(bodyParser.json());
// index
app.get('/', function(req, res) {
res.send('Hello world from express');
});
app.use('/api', router);
// REST API
router.route('/quotes/random')
.get(function(req, res, next) {
var random = Math.floor(Math.random() * quotecount);
Quote.findOne({"index":random},
function (err, result) {
if (err) {
console.log(err);
res.redirect('/quotes/random');
}
res.send(result);
Node - Express Routes