Logo

Java Regex and the Dollar Sign

about 1 year ago | Aishwarya Singhal: Aishwarya Singhal

I came across an interesting problem today that got 3 hrs wasted for no good reason. In my application, I have templates and I replace variables with values that are read from a file. And I use the plain old String.replaceAll to do the job. So it happened this afternoon that I landed upon the [...]

Companies aren't communities

about 1 year ago | Michael Idinopulos: Transparent Office

Companies aren't communities. They aren't forums. Companies are companies. Of course company life has a community aspect, but a lot of social software folks seem to forget that there's a lot more to a company than community. They treat companies...

Stata or R - How to create dynamic variables in R?

about 1 year ago | Prasoon Sharma: Enterprise Software Does not Have to Suck

As we dig deeper into Stata or R debate, a few questions have come up.


Question 1: One of the things Stata does well is the way it constructs new variables (see example below). How to do this in R?



We can rewrite it as-is using for loops in R, which is slow and not elegant. What's the elegant way to write this in R? I haven't used plyr yet... Time to learn it?

Link to question on StackOverflow


Speech by Shankar Abhyakar on Veer Savarkar

about 1 year ago | Niranjan Sarade: InLoveWithNature

Few days ago, I listened to a great speech series (in Marathi language) given by Vidyavachaspati Shankar Abhyankar on Swatantryaveer Vinayak Damodar Savarkar. (http://www.savarkar.org/en/audio)

I have always admired greatness of Savarkar. He was a fearless freedom fighter, social reformer, writer, dramatist, poet, historian, political leader and philosopher to name a few. After listening to the speech, my respect about him got multiplied by thousand times. A good amount of information about Veer Savarkar and some of his books are made available at http://www.savarkar.org/ in both Marathi and English languages. Please read and get inspired !

Vande Mataram !

When Agile becomes Anarchy

about 1 year ago | Lalatendu Das: Interpretations of Technorealism

I have seen successful agile teams innovating on process front..and quite successfully so. While I am in favor of such evolution in Agile ecosystem, what bothers me is the resulting lack of discipline.

One of our high performing project teams has successfully implemented Kanban processes into Scrum framework, but to my surprise, in the process the team has lost focus on some key agile processes. For example, there is neither any sprint commitment (Scrum CTQ*) nor any limit on WIP items of each workflow state (Kanban CTQ*). While the team continues to measure sprint velocity, the complete lack of predictability is equally puzzling (i.e Avg Sprint velocity assumed to be 40 SP**, where as, for last number of quarters team is consistently maintaining a higher velocity). To the credit of this particular project team, it's successful in meeting sponsor expectations (The process works!?..so it seems.)

While some teams can get away with such transient process implementation (like the aforesaid team), in order to be successful over a long run, I would strongly recommend to bring in process rigor.

Agile is already lean on processes, but it requires a disciplined approach towards maximizing value from it's limited set of processes. Keeping with the ethos of 'Inspect and Adapt' if you plan to change any of the existing processes, consider this simple approach:

  • Make sure the process changes doesn't break any of the agile values or practices
  • As a project team, discuss and agree on the new set of processes to be adopted (if possible share with others as well - make it public)
  • As a team commit to the new processes with utmost discipline
Agile without discipline would result in Anarchy.
It may work for you today but you can never be sure how it turns up tomorrow.

Thoughts? Reactions?

*CTQ - Critical To Quality
**SP - Story Points

Concurrency with Fibers and EventMachine

about 1 year ago | Amit Kumar: RubyizednRailified

Concurrency in Rails - a bug that bit me few weeks back. This led me to read in detail about "Reactor Pattern" (EventMachine, Twisted, Node.js) and making requests asynchronous.

Let me take a step back and tell ya what made me read all this.
Think about if, you had to solve a problem of making multiple service calls to complete a response. Doing this sequentially is "old" architecture, where you did not care much about performance. One can definitely argue, why not cache the beast !
Well,

  • what if the data is dynamic
  • what if I care more about CPU Utilization.
Every service requires I/O and everyone knows I/O is blocking. So, while waiting for the request to complete, CPU sits idle doing nothing. It could have fired another service call. This is more easy to say then to solve . This is where evented programming becomes very helpful. Consider all service calls as events which you can register for callbacks. You fire them all together and wait for them to complete. But now these events (ruby threads) compete for CPU cycle (yeah for obvious reasons - green thread). The threads are preempted by OS and there is no way you can control this.

Ruby 1.9 introduced this powerful concept of Fibers - of creating code blocks which can be paused and resumed by application developer. So, we can control when to pause and resume the execution ?? yeah
Moreover they are cheap to spin off new as compared to threads.

So, to achieve concurrency, we can fire fibers as events, each fiber responding back to callbacks.
All sweet !!

Wrote a nice Rails app -> fibered-rails

Going to talk about this in our TCS Rails Conf'11 on 02/17/2011 - see the talk here

Reading Excel in Rails

about 1 year ago | Aishwarya Singhal: Aishwarya Singhal

Whatever the search results say, you probably don’t need a plugin. I had a hard time trying to make parseexcel work and it kept reading my excel file all wrong. I finally have used win32ole which comes bundled up with rails 3. Here’s the source code There are two problems with this: firstly, you need [...]

Some Quick Tips

about 1 year ago | Aishwarya Singhal: Aishwarya Singhal

1. Removing a column from a table in SQLite There’s no straight forward way in SQLite so you need to copy the contents into a new table drop and recreate the table and put the data back in. In short, its a big mess. Thankfully rails manages that for us. 2. Creating static data I [...]

Implementing Pagination in Rails

about 1 year ago | Aishwarya Singhal: Aishwarya Singhal

Implementing pagination in Rails is dead easy. I used a plug in called will_paginate. The usual one that’s downloaded when you say “gem install mislav-will_paginate” didn’t work for me. It kept on escaping the HTML so all I got was garbled text on the screen. The one that did work was ”gem install agnostic-will_paginate”. Once you [...]

Ruby, JQuery and AJAX

about 1 year ago | Aishwarya Singhal: Aishwarya Singhal

Since my last post, I got busy with some pressing project work and Ruby on Rails took the backseat. But I picked it up again last week and, as promised, tried a “real” app. Now Ruby is all cool and stuff, but there are gotchas everywhere and I noticed a few that I thought I’ll [...]

If Powerpoint were designed today..

about 1 year ago | Lalatendu Das: Interpretations of Technorealism

Check out SlideRocket - Enables development of sleek presentations powered with
- Online polling
- Rich Media
- RealTime data
- Online sharing



Which feature(s) do you find to be useful?

20 sec reading

about 1 year ago | Doel Sengupta: Doel

I am following Paulo Coelho's blog these days.
It has a refreshing section named 20 sec reading...was lured by the name itself, it can be possible by an author of his stature only to write such an interesting and intriguing post which can be read in time as short as 20 secs. Like to recommend to read his blog and refresh the mind.

http://paulocoelhoblog.com

Do you really need a Code Beautifier ?

about 1 year ago | Niranjan Sarade: InLoveWithNature

A food of thought! As a good developer, do you really need a Code Beautifier?

This thought came to my mind when I was reviewing my friend's code which was not properly intended for whatever reason and appeared to me as if scribbled on a paper. Soon I got frustrated comprehending the code with my brain muscles stretching out beyond their limits. When I asked the reason behind improper indentation, I got an answer (rather a question) - Do we have a good code beautifier which would properly intend the code without human intervention? That was an unexpected answer to me. There are certainly a lot of paid and open source code beautifier tools available, but do we really need them when we write a code?

Why can't we make it a good practice to properly intend the code when we write? Almost all IDEs provide good facility to have proper indentation and formatting. Why am I emphasizing so much on this? In my opinion, a good readable and logically structured code is necessary not merely for outlook. It actually reflects your mind - your attitude, discipline and neatness. This also brings a very important aspect when you are collaborating amongst your development team.

Yes, when you download a third party code and if that code is not properly formatted, then the code beautifier tools play a good role in making the code clean and readable. The code beautifiers are meant for existing ugly code faces, they are not meant for fresh development!

The ultimate message is - whenever you are creating something, be it a code or anything... make it always beautiful .... :-)

Backbone.js Makes Building JavaScript Applications Fun

about 1 year ago | Alex Rothenberg: Common Sense Software

Like many developers I’ve had a long, complicated relationship with Javascript. Especially with libraries like jquery it’s incredibly easy to add interesting behavior to your pages, but unless you’re very careful its also likely that you’ll end up with a mess of spaghetti javascript. I know as I’ve gotten myself into that mess and abandoned many projects because they were just too hard to change. All this has changed with some of new libraries out there that help you write your javascript following the MVC pattern.

Today I’m going to talk about backbone.js and show how it helped me and two friends build a rich one-page application to understand an exception stack trace. Backbone.js describes itself as supplying structure to JavaScript-heavy applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface.

There are a number of tutorials and examples available out there to get you started. The basic idea is to uses backbone.js to organize your code into models, views and controllers.

What is CodeBuddy

CodeBuddy is the application I’ll describe. It helps you navigate an exception stack raised by your Rails app or any other stack you paste in. I worked on it with Pat Shaughnessy and Daniel Higginbotham and Pat produced a super article describing what CodeBuddy is and how to use it.

There is some server-side code that replaces the Rails Show Exceptions page and syntax highlights a snippet of source code for each line in the stack but for this article I’m going to ignore that and focus on the interactive page and the javascript behind it.

Below is a picture showing a stack trace the background and the code snippet for the currently selected line in front. Now a picture is okay but to really get a sense of it I suggest you follow this link to experience Code Buddy in action - try pressing ↑ or ↓ or double clicking a few lines in the stack then press s.

Code Buddy

There’s a lot going on here and if we had tried building this before discovering backbone.js we probably would have had created a mess - mixing javascript and html that quickly would have become hard to change. I’m going to show you how backbone let us separate the models from the views and create something that was not hard to grow.

Let’s get into the technical details!

Organizing our data in Backbone Models

We want to follow good OO design principles and thinking about this our exception stack is really just a few objects:

  • A Stack

    • has many Addresses
    • knows which Address is selected
  • Each Address has

    • path to a file
    • line number
    • snippet of code

We can build this as a JSON object like

var stackJson = {
  "stack_frames": [
    { "path": "/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb",
      "line": 5,
      "code": "class UsersController < ApplicationController\n..."
    },
    { "path": "/Users/alex/.rvm/.../lib/action_controller/metal/implicit_render.rb",
      "line": 4,
      "code": "module ActionController\n..."
    }
  ],
  "selected": 0
}

The first step is to turn this into backbone models.

// Stack, Address and Addresses
CodeBuddy.backbone.Stack = Backbone.Model.extend({
  initialize: function() {
    this.set({
      addresses: new CodeBuddy.backbone.Addresses(this.get('stack_frames')) 
    })
  }
})

CodeBuddy.backbone.Address = Backbone.Model.extend({
})

CodeBuddy.backbone.Addresses = Backbone.Collection.extend({
  model:CodeBuddy.backbone.Address
})

The way we build a model in backbone is by extending Backbone.Model. When extending we can add custom behavior if we want. In our example we tell the Stack to contain a collection of Address objects in the Addresses collection. We use the backbone collection framework to define Addresses and tell it that it is a collection of Address model objects. These models will use the default backbone behavior for the rest which includes read/write access to its properties get or set.

Now that they’re defined, we’re ready to interact with these models. For example below is what you’d see using the Chrome javascript console (I’m showing the output as comments for readability)

// Using our models in a console
CodeBuddy.stack = new CodeBuddy.backbone.Stack({
  "stack_frames": [
    { "path": "/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb",
      "line": 5,
      "code": "class UsersController < ApplicationController\n..."
    },
    { "path": "/Users/alex/.rvm/.../lib/action_controller/metal/implicit_render.rb",
      "line": 4,
      "code": "module ActionController\n..."
    }
  ],
  "selected": 0
})
// inherits.child

CodeBuddy.stack.get('addresses')
// inherits.child

CodeBuddy.stack.get('addresses').first().get('path')
// "/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb"

CodeBuddy.stack.get('addresses').first().get('code')
// "class UsersController < ApplicationController
// ..."

We now have an object hierarchy with default behavior which we can (and will) extend in a bit but first let’s build some views and get a page we can look at.

Building the UI with Backbone Views

We’re going to build

  • A StackView that contains many AddressViews
  • Each AddressView will display a single line from the stack.
  • Each view will be tied to one of our model objects

It will look something like this:

Code Buddy views on the page

We can start with a StackView that’s tied to the Stack model. Creating a backbone view is very similar to how we created our models - we extend Backbone.View and can override behavior if we want.

CodeBuddy.backbone.StackView = Backbone.View.extend({

  el: $("#stack"),

  initialize: function() {
    this.model.get('addresses').each(this.addOneAddress);
  },
  
  addOneAddress: function(address, index) {
    var view = new CodeBuddy.backbone.AddressView({model: address});
    this.$("#stack").append(view.render().el);
  }
})

In this case we overrode the initializer function to create an AddressView for each address. It also uses jQuery to add the AddressView's html within the page’s #stack element.

To do the iteration we use another powerful javascript library called underscore.js. Underscore.js gives us a ruby-like collection methods letting us write .each(this.addOneAddress). This will iterate over all the addressses calling the addOneAddress function on each one. Underscore.js also gives us erb-like templating we’ll use in the AddressView…let’s take a look at that view.

CodeBuddy.backbone.AddressView = Backbone.View.extend({
  tagName:  "li",

  template: _.template("<span class='container'><%= path %>:<%= line%></span>"),

  initialize: function() {
  },

  render: function() {
    var html = this.template(this.model.toJSON())
    $(this.el).html(html);
    return this;
  }
})

You can see the template and how it does look like erb. It defines the html that will be displayed for each address and its able to access properties in the model like path and line. The template gets applied in the render function with the line this.template(this.model.toJSON()). Finally, tagName is used to wrap this html in an li tag.

Now we can put it all together to see on a page. We can start with a toplevel page that has an element with stack, includes our models and views and tells them to load.

<html>
<body>
  <ul id="stack"></ul>
  <script src="javascripts/code_buddy.js" type="text/javascript"></script>
  <script>
      CodeBuddy.setup({
        "stack_frames": [
          { "path": "/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb",
            "line": 5,
            "code": "class UsersController < ApplicationController\n..."
          },
          { "path": "/Users/alex/.rvm/.../lib/action_controller/metal/implicit_render.rb",
            "line": 4,
            "code": "module ActionController\n..."
          }
        ],
        "selected": 0
      })
  </script>
</body>
</html>

After the page loads and the views render it changes the #stack div to have all this

<ul id="stack">
  <li>
    <span class="container">/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb:5</span>
  </li>
  <li>
    <span class="container">/Users/alex/.rvm/.../lib/action_controller/metal/implicit_render.rb:4</span>
  </li>
</ul>

So far this is a lot of framework and structure for a simple page but now is when it gets interesting and backbone reveals its true power!

Showing code for the selected address

Let’s say we want to mark one address selected and show the code for that one.

Showing Code for selected Addresss

We can start by adding an element to the html called code-viewer

<html>
<body>
  <ul id="stack"></ul>
  <div id="code-viewer">
    <div id="code"></div>
  </div>
  <!-- all the javascript omitted for clarity -->
</body>
</html>

Now we want to create a StackView to put the right code in there

CodeBuddy.backbone.CodeView = Backbone.View.extend({
  el:$("#code-viewer"),
  
  initialize: function() {
  },
  
  render: function() {
    this.$("#code").html(CodeBuddy.stack.selectedAddress().get('code'))
  }
})

In this view we used our models to find which address was selected CodeBuddy.stack.selectedAddress() so let’s add that method.

CodeBuddy.backbone.Stack = Backbone.Model.extend({
  initialize: function() {
    // same code as before
  },

  addresses: function() {
    return this.get('addresses')
  },

  selectedAddress: function() {
    var selected = this.get('selected')
    return this.addresses().at(selected)
  }
})

That’s it, now we have a code view on top of the stack view and our code is still clean and well organized. I’m not afraid to keep going and make our next change.

Changing the selected address

Oh, we just got a new requirement to be able to scroll up and down through the stack and see the code window change as we go.

We add some more functions to our Stack Model so we can change the selection and we also tell it to call the selectionChanged function whenever the selected property changes. Calling a function on a property change is something that’s given to us with backbone events. Getting the view to update itself is also easy we just tell it to with CodeBuddy.codeView.render()

CodeBuddy.backbone.Stack = Backbone.Model.extend({
  initialize: function() {
    this.bind('change:selected', this.selectionChanged);
    // same code as before
  },

  setSelection: function(newSelected) {
    if (newSelected >= 0 && newSelected < this.addresses().size()) {
      this.set({ selected: newSelected })
    }
  },
  
  selectPrevious: function() {
    this.setSelection(this.get('selected') - 1)
  },
  
  selectNext: function() {
    this.setSelection(this.get('selected') + 1)
  }, 

  selectionChanged: function(x) {
    this.addresses().at(x.previousAttributes().selected).view.render()
    this.addresses().at(x.changedAttributes().selected).view.render()
    CodeBuddy.codeView.render()
  },
  
  // all the existing functions remain  
})

The last thing we need to do is give some way for the user to change the selection. We decided to use jQuery Hotkeys to bind to the up and down arrows (↑ or ↓).

CodeBuddy.setStackKeyBindings = function(){
  $(document).bind('keydown', 'up',   CodeBuddy.stack.selectPrevious)
  $(document).bind('keydown', 'down', CodeBuddy.stack.selectNext)
}

Conclusion

I hope this example has shown a little of the power of using backbone.js when you need to write a complex javascript application.
If you want to see the actual application its all on Github in code_buddy.js

This was our first project working with backbone.js and I’m sure there’s much more we can learn but we’ve found that it lets us write modular code with many small methods which feels much closer to writing Ruby than my previous forays into javascript.

Backbone.js makes writing a javascript application fun!

Backbone.js Makes Building JavaScript Applications Fun

about 1 year ago | Alex Rothenberg: Common Sense Software

Like many developers I’ve had a long, complicated relationship with Javascript. Especially with libraries like jquery it’s incredibly easy to add interesting behavior to your pages, but unless you’re very careful its also likely that you’ll end up with a mess of spaghetti javascript. I know as I’ve gotten myself into that mess and abandoned many projects because they were just too hard to change. All this has changed with some of new libraries out there that help you write your javascript following the MVC pattern.

Today I’m going to talk about backbone.js and show how it helped me and two friends build a rich one-page application to understand an exception stack trace. Backbone.js describes itself as supplying structure to JavaScript-heavy applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing application over a RESTful JSON interface.

There are a number of tutorials and examples available out there to get you started. The basic idea is to uses backbone.js to organize your code into models, views and controllers.

What is CodeBuddy

CodeBuddy is the application I’ll describe. It helps you navigate an exception stack raised by your Rails app or any other stack you paste in. I worked on it with Pat Shaughnessy and Daniel Higginbotham and Pat produced a super article describing what CodeBuddy is and how to use it.

There is some server-side code that replaces the Rails Show Exceptions page and syntax highlights a snippet of source code for each line in the stack but for this article I’m going to ignore that and focus on the interactive page and the javascript behind it.

Below is a picture showing a stack trace the background and the code snippet for the currently selected line in front. Now a picture is okay but to really get a sense of it I suggest you follow this link to experience Code Buddy in action - try pressing ↑ or ↓ or double clicking a few lines in the stack then press s.

Code Buddy

There’s a lot going on here and if we had tried building this before discovering backbone.js we probably would have had created a mess - mixing javascript and html that quickly would have become hard to change. I’m going to show you how backbone let us separate the models from the views and create something that was not hard to grow.

Let’s get into the technical details!

Organizing our data in Backbone Models

We want to follow good OO design principles and thinking about this our exception stack is really just a few objects:

  • A Stack

    • has many Addresses
    • knows which Address is selected
  • Each Address has

    • path to a file
    • line number
    • snippet of code

We can build this as a JSON object like

var stackJson = {
  "stack_frames": [
    { "path": "/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb",
      "line": 5,
      "code": "class UsersController < ApplicationController\n..."
    },
    { "path": "/Users/alex/.rvm/.../lib/action_controller/metal/implicit_render.rb",
      "line": 4,
      "code": "module ActionController\n..."
    }
  ],
  "selected": 0
}

The first step is to turn this into backbone models.

// Stack, Address and Addresses
CodeBuddy.backbone.Stack = Backbone.Model.extend({
  initialize: function() {
    this.set({
      addresses: new CodeBuddy.backbone.Addresses(this.get('stack_frames')) 
    })
  }
})

CodeBuddy.backbone.Address = Backbone.Model.extend({
})

CodeBuddy.backbone.Addresses = Backbone.Collection.extend({
  model:CodeBuddy.backbone.Address
})

The way we build a model in backbone is by extending Backbone.Model. When extending we can add custom behavior if we want. In our example we tell the Stack to contain a collection of Address objects in the Addresses collection. We use the backbone collection framework to define Addresses and tell it that it is a collection of Address model objects. These models will use the default backbone behavior for the rest which includes read/write access to its properties get or set.

Now that they’re defined, we’re ready to interact with these models. For example below is what you’d see using the Chrome javascript console (I’m showing the output as comments for readability)

// Using our models in a console
CodeBuddy.stack = new CodeBuddy.backbone.Stack({
  "stack_frames": [
    { "path": "/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb",
      "line": 5,
      "code": "class UsersController < ApplicationController\n..."
    },
    { "path": "/Users/alex/.rvm/.../lib/action_controller/metal/implicit_render.rb",
      "line": 4,
      "code": "module ActionController\n..."
    }
  ],
  "selected": 0
})
// inherits.child

CodeBuddy.stack.get('addresses')
// inherits.child

CodeBuddy.stack.get('addresses').first().get('path')
// "/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb"

CodeBuddy.stack.get('addresses').first().get('code')
// "class UsersController < ApplicationController
// ..."

We now have an object hierarchy with default behavior which we can (and will) extend in a bit but first let’s build some views and get a page we can look at.

Building the UI with Backbone Views

We’re going to build

  • A StackView that contains many AddressViews
  • Each AddressView will display a single line from the stack.
  • Each view will be tied to one of our model objects

It will look something like this:

Code Buddy views on the page

We can start with a StackView that’s tied to the Stack model. Creating a backbone view is very similar to how we created our models - we extend Backbone.View and can override behavior if we want.

CodeBuddy.backbone.StackView = Backbone.View.extend({

  el: $("#stack"),

  initialize: function() {
    this.model.get('addresses').each(this.addOneAddress);
  },
  
  addOneAddress: function(address, index) {
    var view = new CodeBuddy.backbone.AddressView({model: address});
    this.$("#stack").append(view.render().el);
  }
})

In this case we overrode the initializer function to create an AddressView for each address. It also uses jQuery to add the AddressView's html within the page’s #stack element.

To do the iteration we use another powerful javascript library called underscore.js. Underscore.js gives us a ruby-like collection methods letting us write .each(this.addOneAddress). This will iterate over all the addressses calling the addOneAddress function on each one. Underscore.js also gives us erb-like templating we’ll use in the AddressView…let’s take a look at that view.

CodeBuddy.backbone.AddressView = Backbone.View.extend({
  tagName:  "li",

  template: _.template("<span class='container'><%= path %>:<%= line%></span>"),

  initialize: function() {
  },

  render: function() {
    var html = this.template(this.model.toJSON())
    $(this.el).html(html);
    return this;
  }
})

You can see the template and how it does look like erb. It defines the html that will be displayed for each address and its able to access properties in the model like path and line. The template gets applied in the render function with the line this.template(this.model.toJSON()). Finally, tagName is used to wrap this html in an li tag.

Now we can put it all together to see on a page. We can start with a toplevel page that has an element with stack, includes our models and views and tells them to load.

<html>
<body>
  <ul id="stack"></ul>
  <script src="javascripts/code_buddy.js" type="text/javascript"></script>
  <script>
      CodeBuddy.setup({
        "stack_frames": [
          { "path": "/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb",
            "line": 5,
            "code": "class UsersController < ApplicationController\n..."
          },
          { "path": "/Users/alex/.rvm/.../lib/action_controller/metal/implicit_render.rb",
            "line": 4,
            "code": "module ActionController\n..."
          }
        ],
        "selected": 0
      })
  </script>
</body>
</html>

After the page loads and the views render it changes the #stack div to have all this

<ul id="stack">
  <li>
    <span class="container">/Users/alex/ruby/github/test_app/app/controllers/users_controller.rb:5</span>
  </li>
  <li>
    <span class="container">/Users/alex/.rvm/.../lib/action_controller/metal/implicit_render.rb:4</span>
  </li>
</ul>

So far this is a lot of framework and structure for a simple page but now is when it gets interesting and backbone reveals its true power!

Showing code for the selected address

Let’s say we want to mark one address selected and show the code for that one.

Showing Code for selected Addresss

We can start by adding an element to the html called code-viewer

<html>
<body>
  <ul id="stack"></ul>
  <div id="code-viewer">
    <div id="code"></div>
  </div>
  <!-- all the javascript omitted for clarity -->
</body>
</html>

Now we want to create a StackView to put the right code in there

CodeBuddy.backbone.CodeView = Backbone.View.extend({
  el:$("#code-viewer"),
  
  initialize: function() {
  },
  
  render: function() {
    this.$("#code").html(CodeBuddy.stack.selectedAddress().get('code'))
  }
})

In this view we used our models to find which address was selected CodeBuddy.stack.selectedAddress() so let’s add that method.

CodeBuddy.backbone.Stack = Backbone.Model.extend({
  initialize: function() {
    // same code as before
  },

  addresses: function() {
    return this.get('addresses')
  },

  selectedAddress: function() {
    var selected = this.get('selected')
    return this.addresses().at(selected)
  }
})

That’s it, now we have a code view on top of the stack view and our code is still clean and well organized. I’m not afraid to keep going and make our next change.

Changing the selected address

Oh, we just got a new requirement to be able to scroll up and down through the stack and see the code window change as we go.

We add some more functions to our Stack Model so we can change the selection and we also tell it to call the selectionChanged function whenever the selected property changes. Calling a function on a property change is something that’s given to us with backbone events. Getting the view to update itself is also easy we just tell it to with CodeBuddy.codeView.render()

CodeBuddy.backbone.Stack = Backbone.Model.extend({
  initialize: function() {
    this.bind('change:selected', this.selectionChanged);
    // same code as before
  },

  setSelection: function(newSelected) {
    if (newSelected >= 0 && newSelected < this.addresses().size()) {
      this.set({ selected: newSelected })
    }
  },
  
  selectPrevious: function() {
    this.setSelection(this.get('selected') - 1)
  },
  
  selectNext: function() {
    this.setSelection(this.get('selected') + 1)
  }, 

  selectionChanged: function(x) {
    this.addresses().at(x.previousAttributes().selected).view.render()
    this.addresses().at(x.changedAttributes().selected).view.render()
    CodeBuddy.codeView.render()
  },
  
  // all the existing functions remain  
})

The last thing we need to do is give some way for the user to change the selection. We decided to use jQuery Hotkeys to bind to the up and down arrows (↑ or ↓).

CodeBuddy.setStackKeyBindings = function(){
  $(document).bind('keydown', 'up',   CodeBuddy.stack.selectPrevious)
  $(document).bind('keydown', 'down', CodeBuddy.stack.selectNext)
}

Conclusion

I hope this example has shown a little of the power of using backbone.js when you need to write a complex javascript application.
If you want to see the actual application its all on Github in code_buddy.js

This was our first project working with backbone.js and I’m sure there’s much more we can learn but we’ve found that it lets us write modular code with many small methods which feels much closer to writing Ruby than my previous forays into javascript.

Backbone.js makes writing a javascript application fun!

Recommended Reading: The Big Short

about 1 year ago | Lalatendu Das: Interpretations of Technorealism

The fall of 'Lehman Brothers' in the later half of 2008 was a defining moment for me. Not as much for what Lehman stood for as for the resulting job losses in Lehman India (where some of my dear friends were proud employees once).

What I did not realize then, pretty obvious in hindsight, is the fall of Lehman Brothers had a more profound effect on wall street. This event marked the demise of high leverage Investment banking that was a hallmark of USA's capitalistic economy.

How did then this well oiled machine go so wrong? How come top notched financial innovations got punished by the very market they created?

Michael Lewis's 'The Big Short' takes throws light on what caused this catastrophe (biggest recession since 1930s'). A must read for all to understand how the fundamental weaknesses of the system (allowing esoteric high-leveraged deals), action (or rather inaction) of credit rating agencies such as Moody's S&P and above all the greed of Capitalist world joined hands to derail world's biggest economy.

Michael Lewis's deft treatment of such a prosaic topic is commendable. The sensitive handling of key protagonist coupled with thoughtful explanation of exotic financial instruments, makes the book, a compelling read.

Highly recommended.

Stata or R

about 1 year ago | Prasoon Sharma: Enterprise Software Does not Have to Suck

Recently I came across a complex model written in Access with complex SQL queries all over the place. The engineer who was maintaining it and I did some analysis and agreed that the model was using SQL in an unnatural way (things SQL isn't good at) - complex logic, formatting etc. 

We agreed to use SQL and a more powerful programming language to re-build the model. The engineer is familiar with Stata, so he quickly wrote Stata code. When I looked at the Stata code, it looked fairly easy to reproduce it in R. I've posted some R commands for the Stata commands I found in that code. 

What are the advantages of using Stata? Why shouldn't I use R for this?



WhatsApp : Impressive!!!

about 1 year ago | Binoy Shah: Binoy Thinks

I had almost made up my mind that all good mobile applications are meant for Android or Iphone or Blackberries. So when I found that WhatsApp messenger is available for Nokia E63 with Symbian OS, I was pleasantly surprised.

So without any further delay, I downloaded it and installed it using Ovi Store. On installation, what really impressed me was that the app scanned through my contact list and listed the friends who were online on Blackberry or any other mobile.

I am exploring this new App on my phone, but it has impressed me so far.

Who said great things cannot come free.

The website is http://www.whatsapp.com.

Absolutely recommended!!!!

What is work and what is play?

about 1 year ago | Surbhi Bhati: Clean Desk, Jammed drawers

“In Production all servers are running from my ID...isn’t it cool !!”

A friend of mine updated this on his Facebook account some days back. Aren’t we used to see updates that go like "Another bad day at work" on Facebook/Twitter more often?

Rise of social media is changing the norms of everyday communication. You start form sharing anything that you think is cool enough and then you start looking out for things to share and then it comes to a point when you have to share a bad experience. Is this a problem? Answer to this depends upon what your group consists of? And more than that, what have you been sharing and how you handle it. There are pros and cons to it. Let us see how;

For most of us our Facebook friends range from mere acquaintances to childhood friends, to recent friends to activity partners to office colleague and to even supervisors (Last one is true at least in my case ;) ). When my followers are such a mixed group, things I share can be interpreted in different ways. The status update mentioned above got my friend kind of heroic remarks from his friends, but what if a colleague or a supervisor sees this? I am not sure the outcome would be that amusing.

On the other hand, having everyone at one place helps me make my voice heard well. I can actually draw different perspectives from people and generate a lot of food for thought. I can provoke a discussion and catch required amount of attention, and because it reaches beyond my own network (that’s the way Facebook works) I get a good chance to get people interested who I otherwise won’t come across. At those levels it provides you a better networking opportunity even in professional terms; better than LinkedIn or any other professional network for that instance.

Another friend had to make an important deal-breaking presentation to a prospective client. A normal Google search landed him on client’s Facebook profile and he got to know that the client shares his interest in graphology. On his way to office, fortunately he met him in lift and just struck an offhand conversation bringing in the common interest. His presentation went well and they got the deal. I know it did not happen because of the off-had conversation but you can’t deny the fact that he was able to make a personal note with that person before stepping into professional zone. Having that personal pitch helped cool his nerves and it’s anyway good to see a smiling spectator rather than a twisted faced one. I am not sure how many of his competitors had that.

So where this does brings us? Today I don’t communicate with people only when I talk to them. I communicate when they see my comment on any of my Facebook friend’s update. I communicate when they see what place I have checked in. I communicate when I say what video or news article I liked or hated or found hilarious. And then there are incidents like those mentioned above that make us feel that work and play are getting mixed. And it seems to be the case. Social network is inevitably mixing personal and professional lives. The more you express, more you will be able to get out of it. There is a reason people are so active out there. It is because they do benefit from it to a good extent.

You build a web personality the way you share things on social media. The more you share, promote and contribute, more trust you gain from people. You build relationships on web that help you work things out in your real life. It might sound radical or even ridiculous but that is what I am seeing happen. The trend is certainly changing.

We are always taught to hide our weaknesses and show only strengths. The growing social media seems to be changing those norms. Sharing more information is helping people get in better touch rather than threatening privacy as we think to be the case. Does that mean definition of privacy has also changed? The trick is in knowing where to draw the line and the question here is how much to share.

Care to share what you think?

Customizing Toto to support blog post categories

about 1 year ago | Pat Shaughnessy: Pat Shaughnessy - Home

On this blog I categorize my posts using a few tags, such as http://patshaughnessy.net/tags/paperclip or http://patshaughnessy.net/tags/view-mapper for example. Today I’m going to walk through how I customized the Toto blog engine to display these category pages.

Of course I could have gotten categories for free using a different blog engine such as Jekyll or Nesta, but to be honest when I saw Toto’s code for the first time I fell in love with it: concise, elegant and simple. I just couldn’t wait to try to understand how it works and modify it to do something new. I suppose it really is “the 10 second blog-engine for hackers!”

Android 3.0: Honeycomb - Preview

about 1 year ago | Lalatendu Das: Interpretations of Technorealism