Monday, April 16, 2012

Small tutorial to using backbonejs with Rails and Backbone-on-Rails-Gem

A demo Todo explanation with the Backbone-on-Rails gem, that is the background of this discussion, is ready for download here: https://github.com/mulderp/Backbone-on-Rails-todoDemo

1. From server-side to client-side programming

The Rails framework is well known for its nice interaction of views, controllers and models. How these components work with HTTP and a database, is typically explained using a blog application. Client-side programming poses slightly different programming problems. Client-side programming is influenced by intricacies of web browsers and the DOM, which includes presentation details (HTML/CSS) and logic (Javascript). Similarly as JQuery provides a better API to manipulate simple structues in the DOM, the goal of Backbone is to provide a language that facilitates so called "data-driven programming", where a high amount of data changes and events in the DOM are becoming easier to deal with on the client-side.

2. Entering client-side programming
Typically, client-side programming is explained with the help of a Todo application. There is great demo of a Todo application from Jérôme Gravel-Niquet , here:

http://documentcloud.github.com/backbone/examples/todos/index.html

 The HTML of a Todo-List is rather simple, and consist of a 'list' that contains a number of 'todos'. For those, who are new to client-side programming, a different toolset is helpful in solving programming problems. These tools and debugging tricks are:


  • jsfiddle:  An interactive sandbox to play with HTML, CSS and Javascript code. Libraries, such as backbone, can be included too
  • jslint: This tools helps in finding errors in Javascript or JSON data
  • the browser console like firebug in Firefox or in the web developer tools of Chrome:  The console helps in evaluating small pieces of code and variables, and breakpoints can help to understand which context and scope is currently active.
  • console-log: With the console.log() function in Javascript, it's possible to monitor the correct flow of data in the application
  • http://js2coffee.org/ : When using coffeescript, as is advised from Rails 3.1 on, it's helpful to understand the conversion of coffeescript into Javscript



3. Fetching data from the server
The main mechanism in backbone to fetch data is by extending a Backbone.Collection For a todo list, where 'todos' should be fetched from the server, or written to the server, a Todos collection might look like this:


class BackboneOnRailsTodo.Collections.Todos extends Backbone.Collection                                                                                                  
  model: BackboneOnRailsTodo.Models.Todo
  url: '/todos'


The important piece here is the 'url'. Coming from a Rails environment, where an 'url' is only defined in the router, this might be a bit confusing, however, 'routes' in Backbone have a different usage, namely to interact with a client-side URL that is marked by a hashtag (e.g. http://mydomain/todos#list ). As a first test, to see that your collection is working, you can use the browser console and fetch some simple todo json from the server.

This could look like this:


todos = new BackboneOnRailsTodo.Collections.Todos()

Todos
todos.fetch()

Object



Note, the 'new' and '()' in the statement above are important, because otherwise, you get some wrongly initalized object. You can then fill your collection, with todos.fetch()


4. Rendering data with help of views and templates
Once, data is available, render it with help of views

a) Views are some kind of containers, where you put data and recipes (templates), how to render the data. In the Backbone-on-Rails gem, you can easily use the ECO type template, which is some kind of ERB in the coffeescript context. Note, you must address view variables with help of @ from the view, like so:
 
  <%= @todo.get('content') %>


b) Views must be initialized with a model or collection hash, typically looking like this:

 view = new BackboneOnRailsTodo.Views.TodoListIndex(collection: @todos)   

c) Views can be rendered, and for this, the render() function is called together with .el(), that actually gives the HTML of the rendered element

d) In views, unlike as in Ruby, there is not much syntactic sugar by default. A function like 'each' is given by the underscore library, but it's even easier to use the construct  for .. in from backbone


5. When to render views?

a) The rendering of view can easy be tested for development purposes, by using the browser console.
preload / 'reset' function

As the rendering of a view, needs to have a model or collection as input, a collection must be initialized first:

todos = new BackboneOnRailsTodo.Collections.Todos()
todos.fetch()


Then,


view = new BackboneOnRailsTodo.Views.TodoListIndex({collection: todos})

The rendering of a view can be tested with

view.render()

b) In our Todo application we work with 2 views. Similar to the demo Todo app by Jérôme NG as above:

// Todo Item View --> The DOM element for a todo item...
var TodoView = Backbone.View.extend({

and

// The Application --> Our overall **AppView** is the top-level piece of UI.
var AppView = Backbone.View.extend({ .. })


c) For the doing the first, startup rendering of a view, a Backbone router can be instructed to initialize the view:


class BackboneOnRailsTodo.Routers.TodoLists extends Backbone.Router
  routes:
    '': 'index' 


  initialize: ->
    @todos = new BackboneOnRailsTodo.Collections.Todos()
    @todos.fetch()
  
  index: ->
    view = new BackboneOnRailsTodo.Views.TodoListIndex(collection: @todos)                                                                                               
    $('#todo-list').html(view.render().el)

It's important to have at least something in a router, otherwise the Backbone router may not have a 'history' state

There are other ways to initialize views, such as synchronous or asynchronous loading of data and/or view templates. In the example above, the data is provided asynchronous from server side.

6. Handling user interaction
So far, the explanation above can be used to fetch data from the server, and to render it. However, in a rich-client application, events in the DOM, that are issued by user interactions (mouse click, key pressed, etc. ) are importat too.
For having user interaction in the application event binding to DOM elements is used. Event binding events uses either Backbone or JQuery event delegation ('bind' or 'on' functions). To lookup the right DOM elements, the delegation must be bound in the correct context.

This can be a cause for confusion as discussed here:



  • http://stackoverflow.com/questions/9304625/in-backbone-js-how-do-i-bind-a-keyup-to-the-document
In the demo Todo application I use the following strategy to binding to events in the TodoListIndex:

  initialize: ->
    @collection.on('reset', @addAll, this)
    @collection.on('add', this.addOne, this)
    $('#new-todo').on "keypress", {collection: @collection}, @keyTodoInput


Note, the 'add' event works by using a backbone event binding. The 'keypress' event must use a JQuery binding, because the input form is outside the scope of the TodoIndex view.

The event that a new todo is added, is processed with:

  addOne: (todo) ->
    console.log(todo)
    view = new BackboneOnRailsTodo.Views.Todo({model: todo})
    $("#todo-list").append(view.render().el) 

The event that an input is made, is processed with:

  keyTodoInput: (e) ->
    # console.log(event.type, event.keyCode)
    return if (e.keyCode != 13)
    return if (!this.value)
    console.log(e.data.collection)

Thursday, May 26, 2011

Beauty in programming

Ahh... nice day today! Finally, could experience and explore the beauty of programming again after some weeks of social science research. The logics of programming is often hidden behind many doors and dark rooms where light switches must be turned on first.
Well, that happened just today: First, taking a class from a C++ project with more than 100 methods, and 5 related classes. Making simplified versions in Ruby. And finally, seeing some relationships between methods and classes.... the hidden code behind abstractions :)

Well, I tried to post something on stackexchange to ask fellow software developers about their experience with beauty in programming, but not much response yet.

Monday, March 21, 2011

Some models for the design thinking process


Here is a short list on variations on the design thinking process.

The first process can be found on webpages at the d.school at Stanford. We see several stages, with variating degree in intensity: Empathize, Define, Ideate, Prototype, Test and Iterate.
The process starts with reflections on whom to work for, exploring and selecting perspectives, reflections on learning outcomes and prototyping, as well as evaluation of prototypes.

Next, there is a circular model proposed by Tim Brown of Ideo.


Here, we see that Inspiration influences ideation and implementation and vice-versa.

An iterative design thinking process that is taught at TU Munich Business School is shown below:


Here, we start with an analysis phase, a design phase follows, a prototype is build. Then, there is play and review on the experiences.

An approach called "customer journey" to service design can be found here. It is also a circular model, starting with a "pre-service" period, a service period, and a post-service period.

Another circular model to design thinking is given by Prof. Ranjan from India. He calls his model the "hand-heard-head" model of design.

Design of 1st order is about form and function. Design on 2nd order is about Function, Feeling, impact and effect. Design of 3rd order is about Meaning and Purpose.

Still farther East, I. Nonaka proposes a model for innovation and learning that is somewhat similar to design thinking. It is the SECI model of knowledge creation. Nonaka starts with the aspect of empathy and observation, that he calls "socialisation". Here, knowledge that is difficult to articulate is experienced. Then, the implicit knowledge is made explicit by the process of "externalisation". This is mainly about codification of experiences with symbols or models. Third, externalised knowledge is combined in new ways to generate new concepts and ideas. This is called "combination". Last is the process of internalisation, where explicit knowledge is converted again into implicit knowledge in the form of best practices.



A short overview on design-thinkers can be found here.

Wednesday, February 09, 2011

Repertory grid technique

In preparation with my MBA thesis at TU Munich on innovation, I have been looking into the repertory grid technique lately.
The method originated from T. Kelley who wanted to access subjective information without posing a biased frame of reference when interviewing people. Given a specified context (either minimum or full) by providing elements of interests (observations of phenomena), qualitities (or constructs) about these elements are elicited by participants in the interview.

Some web pages that describe the method are:

http://azlanadnan.blogspot.com/2003_11_01_archive.html

http://www.ischool.utexas.edu/~adillon/Journals/Towards%20a%20classification.htm

https://github.com/markheckmann/repgrid

http://webspace.ship.edu/cgboer/qualmethfive.html

http://www.pcp-net.de/papers/ueberbli.htm

http://pages.cpsc.ucalgary.ca/~laf/611/Group/Reperatory_Grids_Exercise.html
http://www.personality-project.org/R/

http://www.ischool.utexas.edu/~adillon/Journals/Towards%20a%20classification.htm


von L BJÖRKLUND - 2005 -
THE REPERTORY GRID TECHNIQUE. 21 more general dispositions or key competencies. The typical textbook items are, at best, indicators of such “habits of mind” ...
citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.98.3538&rep...

http://valeriestewart-repertorygrid.blogspot.com/

Next step: What could elements be of the RGT for a web collaboration system?

Monday, February 07, 2011

The forms of tacit knowledge

So, I am going to explore the role of tacit knowledge to improve our ways of web communication. As a first step, it is interesting to ask what do we understand "tacit knowledge" is?

Here some ideas on tacit knowledge:
* TK is related to subjective information or knowledge. Subjective is often used to contrast objective information.
* TK is related to the context where information is used
* TK and implicit knowledge are related
* TK and affective information is related. Affective information is often used in advertising. Advertising relies heavily on images and metaphors. There are several authors that investigate cognitive processes for advertisment purposes. One of them is C. Scheier.
* In motivation theory, tacit knowledge might be related to intrinsic rewards versus extrinsic rewards. Some ideas on motivation can be found in the context of gaming, such as here ( Usability learning blog )
One of the concepts used here is the concept of Journey.
* TK is related to emotional communication. How can we share stories to find the deeper motivations?
* TK might be related to synthesis and discovery of knowledge rather to analytic knowledge.
* TK might be related to dynamic versus static information, behavior and actions.
* TK might be related to tastes and patterns

What are your ideas on tacit knowledge? Please help!

Friday, February 04, 2011

Implicit and explicit knowledge

From Nonaka's HBR paper "The knowledge-Creating Company", the following insights can be derived.
First, Western companies try to make decisions based on quantifiable data that often is put together into key metrics, such as increased efficiency, lower costs, improved return on investments.
Japanese companies try to use implicit knowledge for new product development. Here, creating knowledge is not only a matter of processing "objective" information, but depends on subjective insights, intuitions, hunches of individual employees. Often, this requires managers to use images, symbols and metaphors. In this view, a company is not a machine but a living organism. In order to arrive at this view, it takes a shared understanding of what a company stands for, where it is going, what kind of world it wants to live in, and how to make that world a reality. Inventing you knowledge is not the provinence of a specialized R&D department, but a way of behaving.
Central to the knowledge creating company is the activity of making personal knowledge available to others.
The process of turning implicit knowledge into explicit knowledge and vice-versa are especially valuable for an organization. In Nonaka's view, these transitions are the interfaces where knowledge is created.
Explicit knowledge are specification that can easily be communicated and shared in today's web communication systems.
For innovation, "tacit" knowledge is often valuable. Tacit knowledge is very subjective and highly personal. As Michael Polanyi said: "We can know more than we can tell."

Sunday, July 18, 2010

interaction and cognitive psychology

once in a while I stumble across new research on cognitive psychology. this is sad news actually:

Mike Scaife

Monday, April 12, 2010

git version control

git is becoming more and more a viable tool to work with content in the cloud, on my local desktop or on a remote server. It's incredible efficient.

Here is a nice summary. 20 commands for every-day Git Git from the viewpoint of a committer and project integrator.

Sunday, March 21, 2010

doing a survey with ruby on rails (part 2)

Now, that the tables and models are setup, we implement the View and Controller layers. The scaffold has given already some start, but we'll change these to give our application a better survey character.

First, the index view of the questions. We want to see a simple list of questions that we have so far, and the associated choices.

So, let's edit this view in /survey/app/views/question/index.html.erb. We remove almost everything and replace it with a unlinked list in html like this:



Note how we have used a second unlinked list to display the choices that are associated with a question, and how the modify and destroy actions are removed to be accessible only from inside the question edit. The question can be edited by clicking on it.

At the moment, we don't have any choices yet in our database. Let's add some with putting "http://0.0.0.0:3000/choices" in the URL of our browser.

I add the following for now: "it's great", "much", "ok", "not much", "green", "blue", "red", "yellow"

Now, we arrive at one of the more difficult parts. Putting checkboxes in the new and edit views of the questions.

First, the new action in /survey/app/views/questions/new.html.erb :

We need to iterate over the choices. We can do this like this:




We also insert the loop in the edit view:




To have a short list in our show view on choices, we add in app/views/questions/show.html.erb:



So, that was part 2. By now, you should have a survey app where an administrator can easily enter questions and associate possible choices with these questions.

Next, we need to have users who can take part in the survey.


Saturday, March 20, 2010

doing a survey with ruby on rails (part 1)

This is a basic tutorial that might help you understand the basics of ruby-on-rails. The idea of the project comes from this stackoverflow.com question. My current rails working environment is 2.3.5.

As with every rails project, in the beginning rails gives you a basic project setup using the model-view-controller pattern.

Let's try:


./ > rails -d mysql survey


The -d option is important to specify the usage of a database right at the start. In general, I use mysql for this, and the provided database.yml may need a bit tweeking the first time, but will soon be functional for many rails projects.

To create and test the database, you want to check with:


./survey/ > rake db:create


if there is no error message.

Coming back to our MVC pattern, at the moment, the directories /survey/app/models, /survey/app/views and /survey/app/controllers are still empty.

Basic resources (what the combination of a view-model-controller often is), can easily be done with scaffolding.

So, let's make a resource for our "question" and one resource for a "choice".


script/generate scaffold question whatabout:string
script/generate scaffold choice desc:string


With


rake db:migrate


we create our new tables in the database.

Now, we need to associate a choice wih a question. We want to select the choices that a user can enter in the survey. So, we use a m:n relationship between choices and questions. (The steps behind this are explained more in detail here, here and here).

So, to implement the associations, we need to modify our table and the models accordingly.

First, we create a helper table with:

script/generate model questions_choice


In the new migration, we add references to our "choices" and "questions" tables like this:

class CreateQuestionsChoices < ActiveRecord::Migration
def self.up
create_table :choices_questions, :id => false do |t|
t.references :choice, :question
t.timestamps
end
end

def self.down
drop_table :choices_questions
end
end


Let's check that we have no problems so far with a:

rake db:migrate


Next, we edit our models:

We say:


# question.rb
class Question < ActiveRecord::Base
has_and_belongs_to_many :choices
end

# choice.rb
class Choice < ActiveRecord::Base
has_and_belongs_to_many :questions
end

# questions_choice.rb
class QuestionsChoice < ActiveRecord::Base
belongs_to :question
belongs_to :choice
end


As a result, we should be able to access the table "Questions" from the table "Choices", and vice versa. "belongs_to", "has_and_belongs_to_many" are method calls of ActiveRecord. In a sense, Ruby let defines us our own domain-specific language easily, and that is basically what Rails is.

To show that the models are working, it is helpful to check with the Ruby interpreter first. For this, we start:


./survey/ > script/console -s


The -s option says we want to use a sandbox, i.e. our modifications in the database are rollbacked after we exit from the console.

So, first

q = Question.new
q.whatabout="Our Rails tutorial"
q.save


gives us a first question where we can add choices to. We do this with


c = Choice.new(:desc => "it's ok")
q.choices << c


Ruby knows from our models how to set the foreign key question_id and choice_id in the join table by using the operator "<<". We can repeat editing and adding new choices for our first question database.

Within the console, we can list all our choices for a question with:


q.choices.each {|choice| puts "#{choice.id} #{choice.desc}"}



In the next part of the tutorial, we will have a look on how we can provide a user interface for our models on questions and choices

Wednesday, December 16, 2009

network computers

web browsers are in essence some form network computers. computers can be a path to information as explained very nice in this talk by eric schmidt http://www.youtube.com/watch?v=cl8bEApvblg

he also explains that the information industry is actually much bigger than the IT industry, and that google sees itself as an information company. Personally, I think one ingredient in a company around information, is the ability to analyse data.

there is a nice book on data analysis here: http://www.google.de/#hl=de&source=hp&q=head+first+data+analysis&btnG=Google-Suche&meta=&aq=f&oq=head+first+data+analysis&fp=c6a75e802a8b0e7

Thursday, October 29, 2009

how can we get smarter?

how can we get smarter? maybe here is an interesting path:
Concept of "collaboratories"

also very interesting innovation marketing lecture by Clayton Christonson: Understand the job of what a customer is trying to accomplish

Christensen is very inspiring. Makes me popup the question if it is better to master the basics or to study with masters directly. This could make an interesting business called "growthcurve.com" where you could record what knowledge and insight you had to master to be at the point where you are now

Thursday, August 13, 2009

distributed applications

internet is all about pushing and pulling information from different places at different times. the basic idea behind this are the URL and the HTTP protocol. Also, the network gets encapsulated by the cloud concept.
An interesting variation on this seems the CouchDB project.
Here is an interesting video:
CouchDB overview

J. Chris Anderson often uses the REST concept and that he has been learning internet programming by "view source" HTML and later rails.

Here is a short tutorial on REST maybe interesting to look into one day:

PHP rest tutorial from yahoo

Sunday, August 09, 2009

webapp with hobo

Hobo sounds similar to holo and it makes me remember starship Enterprise. In any case, hobo is also a framework for making CRUD application with Rails and it helped me to deploy a first experiment of an app to Heroku: electric-moon-35.heroku.com

Some ressources were helpful for learning how to do this:
* First the the heroku quickstart docs
* The docs about debugging with Heroku
* A message in a mail server on problems with plugins and installing gems: NoMethodError undefined method
* That there exists something like and authentication problems with Herokugardens
* The increasingly popular GIT version control and GIT version control

Sunday, July 26, 2009

ruby experiments

wow.. had a really nice time about learning programming web-apps with rails on ruby:

* Heroku: Very convenient Hosting service heroku.com get in touch with cloud computing
* Railcasts: Very nice tricks to get ruby programs working: Railcasts.com
* Sample CRUD app: Vimeo tutorial by eric berry
* More rails tutorials: rails tutorials
* probably my first ruby book rails book

Monday, July 06, 2009

software and computers

wow, this talk is great.

why software is there, Moore's Law, entrepreneurship, relationship between software and engineering, software and business, online learning, access to information:

gates is a really a good speaker

Marketing, getting appraisal is a big part of Software.

Sunday, June 21, 2009

SQL podcasts

interesting list of SQL podcasts:

SQLDownUnder

Unit testing

eclipse webcast

especially towards the end this discussion gets interesting, testing JavaEE, Servlets, etc.

"Not care how a class does something, but only WHAT it is supposed to do."