Sunday, August 26, 2012

Angular.js for ajax CRUD

Its been a busy weekend, not in terms of coding though.  Just did some quick coding now.  This is now a book-markable ajax CRUD talking to conventional REST/JSON backend.

//app.js

angular.module('ratewatcher', ['ngResource']).
 config(function($routeProvider) {
  $routeProvider.
   when('/lenders', {controller:LenderListController, templateUrl:'lender-list.html'}).
   when('/lenders/new', {controller:LenderCreateController, templateUrl:'lender-detail.html'}).
   when('/lenders/:id', {controller:LenderEditController, templateUrl:'lender-detail.html'}).
   otherwise({redirectTo:'/lenders'});
 }).
 factory('Lender', function($resource) {
  return $resource('/lenders/:id', {id: '@id'}, {});
 });

//controllers.js

function LenderListController($scope, Lender) {
  $scope.lenders = Lender.query();
  
  $scope.remove = function(lender) {
   lender.$remove();
  }
}
  
function LenderCreateController($scope, Lender) {
  $scope.save = function() {
    var lender = new Lender({id: 0,
     name: $scope.lender.name, 
     category: $scope.lender.category, 
     url: $scope.lender.url
    });
    
    lender.$save();
  };
}

function LenderEditController($scope, $location, $routeParams, Lender) {
 $scope.lender = Lender.get({id: $routeParams.id});
 
  $scope.save = function() {
   $scope.lender.$save();
   $location.path('/');
  };
}

I thought the scala backend was really concise, but it turns you can also make the front end javascript just as concise.  Coupled with bootstrap css and basic html, this seems pretty good.

Suggested readings:
http://www.angularjs.org/ - Wire Up a Backend example
http://docs.angularjs.org/api/ngResource.$resource
http://jsfiddle.net/johnlindquist/qmNvq/
http://docs.angularjs.org/api/ng.$route

Thursday, August 23, 2012

Angular.js my first few mins impression

I have been looking at Javascript frameworks.  I have experience in GWT and lately trying to learn ember.js.  So far ember.js is really powerful, but the docs is not that great.  Ember.js has made a lot of changes and the only way to learn it seems to be to read the code/api.  Since my javascript is not that good, it was taking me a bit of time to learn the magic of ember.js.  This lead to me look again a bit, I found angular.js because it was in google's CDN api.

Having read the watch and read the front page of angular.js it seems to be just as powerful as ember.js.  Its got bi-directional binding, a template engine, name spaces.  The terminology they have is FP (ala Scala).  They have apply, future promise.  So gave a try.

function LenderController($scope, $http) {
 $scope.lenders = [];
 
  $scope.all = function() {
    $http.get('/lenders').success(function(data) {
      $scope.lenders = data;
    });
  };
}

<div class="span10" ng-controller="LenderController">
    <table class="table striped">
        <tr> 
            <th>Name</th><th>Category</th><th>Url</th> 
        </tr>
        <tr ng-repeat="lender in lenders"> 
            <td>{{lender.name}}</td> <td>{{lender.category}}</td> <td>{{lender.url}}</td> 
        </tr>
    </table>
    <a href="" ng-click="all()">fetch all</a>
</div>
Pretty short and direct code for fetching from json/rest backend and displaying it on the view.  I think Angular.js is powerful and yet easy for a newbie to pickup.  That is my first few mins impression of it.

Thursday, July 12, 2012

Ruby was shiny before compared to Java, Tcl and Perl. Isn't as shiny when its beside Scala now.

Just looking at Ruby again.  My first encounter with Ruby like most people is through ROR, it was a few years back (era 1.x or maybe before that).  It was a very nice language and at that time, it wasn't that popular.  I did however convince a colleague of mine to push ROR with the help of Bruce Tate's From Java To Ruby book.  He was successful in getting ROR into a Java EE environment.  I had a quick glance of Ruby again today and in tutorial there was this code:
class MegaGreeter
  attr_accessor :names

  # Create the object
  def initialize(names = "World")
    @names = names
  end

  # Say hi to everybody
  def say_hi
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("each")

      # @names is a list of some kind, iterate!
      @names.each do |name|
        puts "Hello #{name}!"
      end
    else
      puts "Hello #{@names}!"
    end
  end

  # Say bye to everybody
  def say_bye
    if @names.nil?
      puts "..."
    elsif @names.respond_to?("join")
      # Join the list elements with commas
      puts "Goodbye #{@names.join(", ")}.  Come back soon!"
    else
      puts "Goodbye #{@names}.  Come back soon!"
    end
  end

end


if __FILE__ == $0
  mg = MegaGreeter.new
  mg.say_hi
  mg.say_bye

  # Change name to be "Zeke"
  mg.names = "Zeke"
  mg.say_hi
  mg.say_bye

  # Change the name to an array of names
  mg.names = ["Albert", "Brenda", "Charles",
    "Dave", "Englebert"]
  mg.say_hi
  mg.say_bye

  # Change to nil
  mg.names = nil
  mg.say_hi
  mg.say_bye
end
It's nice and concise, however it doesn't stand out as much as before.   My comparison was Java, Tcl and Perl a few years ago.  I then did a quick copy and paste, translated it to Scala.

class MegaGreeter(var names: Any = List("World")) {
 
  def say_hi {
    names match {
      case null => println("...")
      case listOfNames: List[String] => listOfNames foreach (n => println("Hello " + n)) 
      case _ => println("Hello " + names)
    }
  }

  def say_bye {
    names match {
      case null => println("...")
      case listOfNames: List[String] => println("Goodbye " + listOfNames mkString(",") + ".  Come back soon!") 
      case _ => println("Goodbye " + names + ".  Come back soon!")
    }
  }
}

object MegaGreeter {
  def main(args: Array[String]) {
    val mg = new MegaGreeter
    mg.say_hi
    mg.say_bye

    // Change name to be "Zeke"
    mg.names = "Zeke"
    mg.say_hi
    mg.say_bye

    // Change the name to an array of names
    mg.names = List("Albert", "Brenda", "Charles",
            "Dave", "Englebert")
    mg.say_hi
    mg.say_bye

    // Change to nil
    mg.names = null
    mg.say_hi
    mg.say_bye
  }
}
Above is not really Scala idiomatic, but close to the original Ruby code especially how the class is created and used.  Ruby still looks nice, but not as shiny as a few years ago.  I am not here to say Scala is better than Ruby, but more of what is shiny before may not be as shiny today.  Just like Java was shiny when I first time used it about 1996, it seems these days people see Java as the wart language.  Scala will loose its shiny appeal in the next few years too.

I also been using the term "shiny", as its really about appeal.  I still use Java and occasionally Perl, even if the are not shiny anymore.  These older languages are still great in their own right.  C is still cool these days.. I think.

Thursday, June 28, 2012

Coin problem, how do you solve it?

My son has this typical homework problem.  If you have 10c, 20c and 1 dollar.  How many ways can you make $2?

I am pretty sure there should be a combination formula for it, but I forgot.  So I tried google but seems there is no formula

http://mathforum.org/library/drmath/view/57913.html

Is there really no formula?

Anyway so he started to make a table of combination.  I told him I better start to see if I can code it, maybe it would help him to verify if the table of combination is correct.  I came up w/ this.  I hope its right otherwise his table of combination is wrong and my code is wrong.

val twoDollars = 200

val coinsCombo = for ( oneDollar <- 0 to (twoDollars/100);
 twentyCents <- 0 to (twoDollars/20);
 tenCents <- 0 to (twoDollars/10);
 if (oneDollar * 100 + twentyCents * 20 + tenCents * 10 == twoDollars) 
) yield (oneDollar, twentyCents, tenCents)
 
coinsCombo foreach println

println(coinsCombo.size)

Explaining C++, Java and Scala to my son

Last night my son was asking about computers again.  I think the conversation came about, what language is on my screen.  I told him its Java and Scala.  I talked about what is assembly, C, C++ and Objective-C and how it relates to Scratch and Kojo.

He asked about why it was named as C++, then I showed him a Java typical loop which is based C where we increment a counter.

int c = 0;
while (c <= 10) {
 System.out.println(c);
 c++;
}



He asked how the loop will be done in Scala.  I started w/ a for comprehension, as he is familiar w/ loops on Scratch and Kojo.

for (c <- 0 to 10) {
 println(c)
}
Then he asked me about the for, <-, etc.

I then changed the code into

0 to 10 foreach println


His reaction "that is so awesome it's like english!"

Sunday, June 3, 2012

misconception about h2 in memory db

Seems sometimes I have seen h2 url connection as "jdbc:h2:mem", which is different from "jdbc:h2:mem:".  The former will create a persistent db in the current path db called mem, the later will create a in memory db.  The official docs explains in in more detail h2 docs.

A good way to know if its in memory or not is just check your current path.  If you have mem.h2.db and  mem.trace.db on the file system, then you are not using the in memory db.

Most of the time though more than 1 connection is needed.  The first reaction is to remove the extra ":", rather than looking at the docs.  The correct fix will be to name the memory db such as "jdbc:h2:mem:foo".  Or if you use JPA sometimes the abstraction is just to thick, and most developers forget how connections are managed.  A connection is closed per test, in general this is the last connection which leads to new db across a test suite.  So to keep the db alive through out the lifetime of the JVM just add ";DB_CLOSE_DELAY=-1"

Sunday, May 27, 2012

Short comparison of Ember.js and GWT

Its been a while since I posted anything here, really hard to make continuous post.  Well try again for the n-th time.

I have been using Google Web Toolkit (GWT) for while, as this is what we use at work.  Its pretty good and has lots of positives, however it also has it's own negatives.

Lets go with the positives first:
  • For some people that knows Java they don't have to learn JS to develop full featured web apps
  • Existing java tooling works on GWT projects.  Re-factoring, IDE support, etc.
  • Performance of GWT is still the best among any JS frameworks
  • Pretty good documentation and examples
Now for the negatives:
  • Not learning JS, or some people will need to learn Java to develop JS code  
  • GWT seems to be on its own eco system outside of the wider JS eco system
  • Sometimes hard to control the html, making iterative changes with a web designer significantly more harder.  This is even using ui binder
  • REST/JSON still seems to be 2nd citizen in GWT.  There is autobeans in GWT now, however still lots of plumbing to do or use 3rd party library.
Using GWT to architect a full blown web app is great.  Using established patterns such as Model View Presenter (MVP), a cousin of the more popular Model View Controller (MVC) pattern.  For the past few years there has been a lot of JS MVC frameworks coming out.  A quick look of the Todo MVC project will give us a lot of different implementation.  (The GWT implementation hasn't been pulled yet).  One of the JS MVC framework that's been gathering a bit of attention is Ember.js.

I gave ember.js a try over the weekend, its been initially a bit frustrating.  Like always when you learn something new, sometimes we just need to unlearn our own old learnings.  Ember documentation is a bit confusing, as its formatted on how to use the different features.  Some of the materials I have found to helpful in getting me running are:


After things started to fall in place, ember.js seems to be pretty straight forward.  Compared to GWT there is really significantly less abstractions.  As ember.js really tries get you in the middle of JS, HTML and CSS.  I am still unsure on how unit testing will be done, haven't look at ember data yet, etc.  However with this initial code:

var App = Em.Application.create();

App.Plant = Ember.Object.extend({
 id: 0,
 name: null,
 description: null
});

App.PlantsView = Em.View.extend({
 plantsBinding: 'App.PlantsController.content'
});


App.PlantsController = Em.ArrayProxy.create({
 content: [],
 
 init: function() {
  var me = this;
  var url = 'http://localhost/plants';
  $.getJSON(url,function(data){
    me.set('content', []);
    $(data.plants).each(function(index,value){
        var plant = App.Plant.create({
            id: value.id,
            name: value.name,
            description: value.description,
        });
        me.pushObject(plant);
    });
  });
 }
 
});

  

As you can see its really straight forward to get data from a rest/json server.  I have an equivalent GWT project, but its too big to post here.  However the equivalent GWT functionality would include.  A model class, a ui binder file, an entry point class, a presenter interface, a view interface, a presenter implementation, a view implementation, http get code, etc.

This doesn't mean longer code is worse code, I am not in the camp of Java is bad too much typing.  I still use Java, although less these days as Scala has pretty much filled the space.  Even with the above code, one can see JS short coming of not having name spaces and no real support for OOP.  However one can see also there is a lot less boiler plate and more natural integration with JS and HTML.  When I mean less boiler, I do not mean about Java's verbose code but the bindings are straight forward.  More natural integration, I just used jQuery's getJSON function straight out of the box and handlebars' template inside html.  GWT has JSNI to call jQuery, but that is less natural and not used often.

Ember.js seems to be promising for organizing web apps.  Then coupled with other mature JS frameworks like jQuery, I think it may make GWT a bit heavy for some use cases.  I am still thinking of looking at Scala+GWT, aside from getting to use Scala to do JS I don't see a lot of difference from normal GWT.