Getting started with Duby and MongoDB

I first talked about Duby back in November. The project has since evolved, there's now more features and it's more usable. I'm able to run MongoDB so I decided to share it. If you know nothing about Duby, read the README.

NOTE: The following example is based on the java example from the mongo-java-driver repo.

Setup

We first need to download the MongoDB jar and add its path to CLASSPATH:

$ export CLASSPATH=.:/my/path/to/mongo-1.2.jar

Then we create our Duby file we name MongoTest.duby.

Connection to MongoDB

We start by importing all we need:

import com.mongodb.Mongo
import com.mongodb.DBCollection
import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.mongodb.DBCursor
import com.mongodb.DB

import java.util.Set
import java.util.List

Then get the DB connection:

begin
  m = Mongo.new
  db = m.getDB "mydb"
  # the rest of the code will go here
rescue Exception
end

Cool new feature: Iterators

One reason I love Ruby is because iterators are nice! This feature landed in Duby a while ago and it's just a pleasure to use it (here to display collection names):

colls = db.getCollectionNames

colls.each do |coll|
  puts coll
end

Inserting a new document

To insert a new document, we must get a collection:

testColl = db.getCollection "testCollection"
testColl.drop # drop the data from previous test

To build a new document we need to use BasicDBObject as a container and there's a BasicDBObject#put(key, value) to add information:

doc = BasicDBObject.new
doc.put "name", "MongoDB"
doc.put "type", "database"
doc.put "count", 1

info = BasicDBObject.new
info.put "x", 203
info.put "y", 102

doc.put "info", info

Of course we can put a BasicDBObject inside another BasicDBObject. And here's how to insert the document we've just build:

testColl.insert(doc)

Getting an existing document

Nothing really to say about how to get the document we've just inserted:

myDoc = testColl.findOne
puts myDoc

Executing the file

I hasn't been able to run the file via duby MongoTest.duby I had to compile it then call it with Java dubyc -java MongoTest.duby && javac MongoTest.java && java MongoTest

Thoughts about Duby

  • dubyc -java converts Duby code to Java code. So you don't have to worry about performance.
  • Duby code really feels like Ruby. And this feeling's getting more and more true.
  • You can create a Duby class and use it in your Java code (unlike JRuby). It's because "Duby is Java with Ruby syntax". And it's wonderful.
  • The true awesomeness is that you can create Android applications with Duby! Check out this example.

Are you excited now? You should be and try Duby right now!

Getting started with Duby and MongoDB

I first talked about Duby back in November. The project has since evolved, there’s now more features and it’s more usable. I’m able to run MongoDB so I decided to share it. If you know nothing about Duby, read the README.

NOTE: The following example is based on the java example from the mongo-java-driver repo.

Setup

We first need to download the MongoDB jar and add its path to CLASSPATH:

$ export CLASSPATH=.:/my/path/to/mongo-1.2.jar

Then we create our Duby file we name MongoTest.duby.

Connection to MongoDB

We start by importing all we need:

Then get the DB connection:

Cool new feature: Iterators

One reason I love Ruby is because iterators are nice! This feature landed in Duby a while ago and it’s just a pleasure to use it (here to display collection names):

Inserting a new document

To insert a new document, we must get a collection:

To build a new document we need to use BasicDBObject as a container and there’s a BasicDBObject#put(key, value) to add information:

Of course we can put a BasicDBObject inside another BasicDBObject. And here’s how to insert the document we’ve just build:

Getting an existing document

Nothing really to say about how to get the document we’ve just inserted:

Executing the file

I hasn’t been able to run the file via duby MongoTest.duby I had to compile it then call it with Java dubyc -java MongoTest.duby && javac MongoTest.java && java MongoTest

Thoughts about Duby

  • dubyc -java converts Duby code to Java code. So you don’t have to worry about performance.
  • Duby code really feels like Ruby. And this feeling’s getting more and more true.
  • You can create a Duby class and use it in your Java code (unlike JRuby). It’s because “Duby is Java with Ruby syntax”. And it’s wonderful.
  • The true awesomeness is that you can create Android applications with Duby! Check out this example.

Are you excited now? You should be and try Duby right now!

Store Rails sessions in MongoDB

There are a few built-in session stores in Rails but if you want to store them in MongoDB (or anything not using ActiveRecord) there's nothing. Not anymore with mongo_session_store!

NOTE: The project was initially created by Chris Brickley with MongoMapper support but without Mongoid support and it was not in a gem.

Usage with MongoMapper

First we load the gem:

config.gem "mongoid"
config.gem "mongo_session_store"

Don't forget to create an initializer to add the connection to the database. Then configure Rails to use MongoMapper for sessions (in the session store initializer):

config.gem "mongo_mapper"
config.gem "mongo_session_store", :lib => "mongo_session_store/mongo_mapper"

Usage with Mongoid

It's almost the same with Mongoid. First setup the environment correctly:

require "mongo_session_store/mongoid"
ActionController::Base.session_store = :mongoid_store

Then the session store initializer:

ActionController::Base.session_store = :mongo_mapper_store

NOTE: Mongoid acts a bit differently than MongoMapper but I havn't had the time to fix the issue.

Next

I'm gonna add some tests, try to have the same usage for Mongoid and MongoMapper and add Rails 3 support. But if you want some other things please fork it.

Store Rails sessions in MongoDB

There are a few built-in session stores in Rails but if you want to store them in MongoDB (or anything not using ActiveRecord) there’s nothing. Not anymore with mongo_session_store!

NOTE: The project was initially created by Chris Brickley with MongoMapper support but without Mongoid support and it was not in a gem.

Usage with MongoMapper

First we load the gem:

Don’t forget to create an initializer to add the connection to the database. Then configure Rails to use MongoMapper for sessions (in the session store initializer):

Usage with Mongoid

It’s almost the same with Mongoid. First setup the environment correctly:

Then the session store initializer:

NOTE: Mongoid acts a bit differently than MongoMapper but I havn’t had the time to fix the issue.

Next

I’m gonna add some tests, try to have the same usage for Mongoid and MongoMapper and add Rails 3 support. But if you want some other things please fork it.

MVC with Node.js - Which modules?

When you start a new technology you may be lost. Node.js is young (1 year today) but there's already a bunch of frameworks (express seems to be the most advanced) and a lot of modules. The best way to begin is to explore the ecosystem. To do that, let's create our own Model-View-Controller stack.

NOTE: The whole example is available on GitHub and not all the code is in the article, so be sure to check it out.

Models

There's a lot of modules for databases and some of them have ORMs. We can use Redis, MongoDB, CouchDB, Tokyo Cabinet, Postgres, Sqlite 3, Riak... For this example we're going to use node-dirty which do not require any database installation. node-dirty is a fast JSON store and it's easy to use, have a look at the following code:

/* Requirements */
require.paths.unshift("./vendor/node-dirty/lib");

var sys = require("sys"),
    Dirty = require("dirty").Dirty;

/* Model */
var posts = new Dirty("posts.dirty", { flushInterval: 10 });

/* Persistence */
var post  = { title: "Awesome post" };
posts.add(post);

/* Querying */
sys.puts(posts.get(post._id).title);

Views

Now we have data we will need views to display them. I've already written something about Mustache.js and for this example I'm gonna use it too but there are other modules available for templating. You can use EJS, HAML, Sass (for css only)...

To use Mustache.js, don't forget to use the one from the commonjs branch (master will not work with Node.js). There's another implementation faster and with built-in async named Mu.

Controllers

The important part here is not the controller itself because it's just a function which will be called by the router. There are some routers but the most interesting is Scylla mainly because it uses EJSGI (an async Rack-like interface for Javascript).

With Scylla we're defining the route with a string containing the HTTP verb and the pattern. Then we bind a function to it.

/* Requirements */
require.paths.unshift("./vendor/ejsgi/lib");
require.paths.unshift("./vendor/node-scylla/lib");

var scylla = require("scylla"),
    ejsgi = require("ejsgi");

/* Controller */
var HomeController = {
  index: function(req) {
    var body = "Hello World!";

    var res = {
      body: new req.jsgi.stream(),
      status: 200,
      headers: {
        "content-type": "text/html",
        "content-length": body.length
      }
    };
    res.body.write(body);
    res.body.close();

    return res;
  }
};

/* Router */
function Router() { scylla.Base.call(this); }
Router.prototype = Object.create(scylla.Base.prototype);
process.mixin(Router.prototype, { "GET /": HomeController.index });

/* Server */
ejsgi.Server(new Router().adapter("ejsgi"), "localhost", 8000).start();

NOTE: I included the router stuff in the controller part because most of the code is in the controller.

Conclusion

As we've seen there are a lot of modules for each part of the MVC stack. It's kinda difficult to choose but it's mainly about what you like (which database you want to use, which templating engine you like and which is the most powerful router).

Most frameworks for Node.js are not fully agnostic (nor fully opiniated) yet so it can be a dealbreaker if you like things that ain't in a framework you want to use. If you're like this you can comment the article and write about your preferences. It will maybe ease the choice for newcomers in the Node.s world.

MVC with Node.js - Which modules?

When you start a new technology you may be lost. Node.js is young (1 year today) but there’s already a bunch of frameworks (express seems to be the most advanced) and a lot of modules. The best way to begin is to explore the ecosystem. To do that, let’s create our own Model-View-Controller stack.

NOTE: The whole example is available on GitHub and not all the code is in the article, so be sure to check it out.

Models

There’s a lot of modules for databases and some of them have ORMs. We can use Redis, MongoDB, CouchDB, Tokyo Cabinet, Postgres, Sqlite 3, Riak… For this example we’re going to use node-dirty which do not require any database installation. node-dirty is a fast JSON store and it’s easy to use, have a look at the following code:

Views

Now we have data we will need views to display them. I’ve already written something about Mustache.js and for this example I’m gonna use it too but there are other modules available for templating. You can use EJS, HAML, Sass (for css only)…

To use Mustache.js, don’t forget to use the one from the commonjs branch (master will not work with Node.js). There’s another implementation faster and with built-in async named Mu.

Controllers

The important part here is not the controller itself because it’s just a function which will be called by the router. There are some routers but the most interesting is Scylla mainly because it uses EJSGI (an async Rack-like interface for Javascript).

With Scylla we’re defining the route with a string containing the HTTP verb and the pattern. Then we bind a function to it.

NOTE: I included the router stuff in the controller part because most of the code is in the controller.

Conclusion

As we’ve seen there are a lot of modules for each part of the MVC stack. It’s kinda difficult to choose but it’s mainly about what you like (which database you want to use, which templating engine you like and which is the most powerful router).

Most frameworks for Node.js are not fully agnostic (nor fully opiniated) yet so it can be a dealbreaker if you like things that ain’t in a framework you want to use. If you’re like this you can comment the article and write about your preferences. It will maybe ease the choice for newcomers in the Node.s world.

Dix-huitième Apéro Ruby de Paris.rb / Ruby France : spécial GitHub

Paris.rb, groupe local de l’association Ruby France, organise son dix-huitième Apéro Ruby, ouvert à tous, rubyistes débutants ou confirmés. Cette rencontre se déroulera mardi 16 février 2010, à partir de 20h, à Dune , 18, avenue Claude Vellefaux 75010 Paris, Métro Colonel Fabien ou Métro Goncourt (voir plan ou voir sur Google Maps Street View ).

Nous aurons l’honneur et la joie de recevoir les biens connus Scott Chacon (expert Git) et PJ Hyett (err.the_blog ) de GitHub . Scott Chacon en profitera pour faire un lightning-talk sur un des ses projets : ShowOff. Cela peut être aussi l’occasion pour vous de leur poser des questions sur GitHub

Vous pouvez me signaler votre venue si vous le souhaitez : mon adresse jftran (at) rubyfrance (point) org ou twitter @underflow_.

À bientôt !

Jean-François.

à noter que si vous ne pouvez venir mardi, vous avez également une chance de rencontrer Scott et PJ au GitHub Drinkup du lendemain mercredi 17 février Scott y fera un lightning talk sur Git.

Dix-huitième Apéro Ruby de Paris.rb / Ruby France : spécial GitHub

Paris.rb, groupe local de l’association Ruby France, organise son dix-huitième Apéro Ruby, ouvert à tous, rubyistes débutants ou confirmés. Cette rencontre se déroulera mardi 16 février 2010, à partir de 20h, à Dune , 18, avenue Claude Vellefaux 75010 Paris, Métro Colonel Fabien ou Métro Goncourt (voir plan ou voir sur Google Maps Street View ).

Nous aurons l’honneur et la joie de recevoir les biens connus Scott Chacon (expert Git) et PJ Hyett (err.the_blog ) de GitHub . Scott Chacon en profitera pour faire un lightning-talk sur un des ses projets : ShowOff. Cela peut être aussi l’occasion pour vous de leur poser des questions sur GitHub

Vous pouvez me signaler votre venue si vous le souhaitez : mon adresse jftran (at) rubyfrance (point) org ou twitter @underflow_.

À bientôt !

Jean-François.

à noter que si vous ne pouvez venir mardi, vous avez également une chance de rencontrer Scott et PJ au GitHub Drinkup du lendemain mercredi 17 février Scott y fera un lightning talk sur Git.

FrenchRails compatible Rails 3 (enfin, je crois)

Mon petit plugin french_rails est maintenant compatible avec Rails 3. La version 0.2 vient d'être publiée sur Gemcutter, et j'ai pu l'utiliser sur une application de test en Rails 3 beta. Vous devriez donc pouvoir faire de même.

Design refresh thanks to CSS3

I have talked about it on my twitter account it's now there. Here's a small design refresh for Boldr. The HTML code has not changed it's just a new CSS. I was using HTML5 since the beginning. Meanwhile, I was not using CSS3 at all. I decided to do something and now I'm using @font-face for the titles, @font-face and rounded corners for the logo and CSS Animations for the links. There will be more details in a series of CSS3 articles I'll be writing soon.

And the browser compatibility is pretty large:

  • @font-face and rounded corners should be OK with the majority of the browsers (including IE6, 7 and 8).
  • CSS Animations should be OK with Safari/Chrome/WebKit and Firefox nightlies.

It's awesome to see that you can do a bit of CSS3 even with Internet Explorer and I will do more and more CSS3 in the next iterations.

I added Intense Debate to the articles, so if you have any suggestions or comments about the design you can tell me this here.