15 minutes Implementation of Rails-like ActiveRecord in JavaScript

Posted on August 31, 2009 by Fernando Trasviña

Categories: Dev NewsElastic

I was trying to design an api for a large application and of course i was using javaScript. So in order to try the feeling of the application design without code it i started up my firebug and started coding a simple active record. so this is what i tried in 15 mins aprox.

here is the result.

Elastic = {
    Installation : (function(){
        var Installation           = function(){};
        Installation.prototype     = {
            domain_name: ‘x’,
            save: function(){
                this.id = Date.now() + Math.random();
                Elastic.Installation.installations.push(this);
                return this;
            }
        };
        Installation.installations = [];
        Installation.all           = function(){
            return Installation.installations;
        };
        Installation.new = function(){
            return new Installation();
        };
        Installation.find = function(id){
            var installations = Installation.installations;
            for(var i = 0; i < installations.length; i++){
                 if(installations[i].id == id){
                     return installations[i];
                 }
            }
            return null;
        };
        Installation.find_by = function(key){
            var finder = function(value){
                var installations = Installation.installations;
                var found = [];
                for(var i = 0; i < installations.length; i++){
                    if(installations[i][key] == value){
                        found.push(installations[i]);
                    }
                }
                return found;
            };
            return finder;
        };
        return Installation;
    })()
};
var installation_id = Elastic.Installation.new().save().id;
var installation_id = Elastic.Installation.new().save().id;
var y = Elastic.Installation.new();
var installations_on_x = Elastic.Installation.find_by('domain_name')('x');
installations_on_x

its kind of cool how JavaScript can be used to try things fast, and with some work you could actually do some serious coding.

firebug as a fast IDE for testing

firebug as a fast IDE for testing

If you enjoy this post, please share it.
  • Digg
  • Reddit
  • DZone
  • del.icio.us
  • StumbleUpon
  • Technorati
  • LinkedIn
  • TwitThis
  • E-mail this story to a friend!

2 Comments »

bucabay says:

I love how dynamic JavaScript is. It makes prototyping ideas so easy, fast and elegant.

I only wish the Firefox console supported JS highlighiting. Would make prototyping in JS even easier.

Fernando Trasviña says:

yeah that would totally rock, firebug is my primary IDE for js

Leave your comment
Copyright © 2009 Elasticss.com. All rights reserved.
Made with Elastic