inspiring things

by Michał Kuklis on 14/01/2012

Here is the list of talks, presentations, movies which inspired me in some ways:

1. Steve Jobs’ 2005 Stanford Commencement Address

2. David Heinemeier Hansson at Startup School 08

3. Web 2.0 Expo NY: Gary Vaynerchuk

4. The Holstee Manifesto: Lifecycle Video

Please let me know if you run into any interesting talks I will keep adding them here.

No Comments

Node.js libs for realtime web apps

by Michał Kuklis on 26/09/2011

Looks like the number of frameworks/libs/tools available for “realtime” web apps is growing. I’ve been following them since socket.io appeared for the first time. Below is the list of tools I ran into in the past. I will try to keep this list up to date.

  1. socket.io
  2. nowjs
  3. faye
  4. juggernaut
No Comments

Extending Jasmine Matchers

by Michał Kuklis on 3/07/2011

Jasmine is a behavior-driven development framework for testing JavaScript from Pivotal Labs (I believe Rajan Agaskar was/is the original author). I’ve been using Jasmine for a while now to test my JavaScript code. Today I ran into interesting situation where I wanted to test events bound to jQuery element. Basically by writing code like this:

$('#el').bind('click', function (e) {
  // handler code goes here
});

I wanted to know if element $(‘#el’) had any events attached to it. I looked around but couldn’t find any predefined matchers in jasmine or jasmine-jquery to accomplish it. I realized that it’s pretty easy to extend jasmine and define my own matchers (which is pretty cool).

Here is how you can do it:

First define your new matchers:

var eventMatchers = {
  toHaveEvent: function (event) {  
    var data = jQuery.data(this.actual.get(0));
    for (obj in data) {
      if (data.hasOwnProperty(obj)) {
        for (eventName in data[obj].events) {
          if (data[obj].events.hasOwnProperty(eventName)) {
            if (event === eventName) {
              return true;
            }
          }
        }
      }
    }
    return false;
  }
};

Then in your spec add your handlers inside beforeEach:

describe("Element", function () {
  beforeEach(function () {
    this.addMatchers(eventMatchers);
  });
});

That’s it! Now you can use your new matchers inside your spec. In this case I was able to use it like this:

describe("Element", function () {
  beforeEach(function () {
    this.addMatchers(eventMatchers);
  });
 
  describe("when event attached", function () {
    it("should contain attached event", function () {
      setFixtures('<div id="el"></div>');
      $('#el').bind('click', function () {});
      expect($('#el')).toHaveEvent('click');
    });
  });
});
No Comments

ssh without a hostname and password

by Michał Kuklis on 15/06/2011

Often I have to login to different machines. It’s annoying to always type the full hostname and then password. So here is what you can do to avoid typing too much:

1. On your local machine create a private and public key:

ssh-keygen -t rsa

by default 2 keys will be created (id_rsa, id_rsa.pub) under ~/.ssh

2. Create config file under ~/.ssh

touch ~/.ssh/config

3. Add your connection information to config file:

Host HOST_ALIAS # can be anything you want
Hostname HOST_NAME # example.com
User USERNAME
port PORT

4. Create .ssh folder on the remote machine from your local machine (you will be prompted for the password):

ssh HOST_ALIAS mkdir -p .ssh

5. Finally append your new public key id_rsa.pub to ~/.ssh/authorized_keys on your remote machine (you will be prompted for the password one last time):

cat ~/.ssh/id_rsa.pub | ssh HOST_ALIAS 'cat >> .ssh/authorized_keys'

That’s all! Now every time you want to login to your remote machine you can type:

ssh HOST_ALIAS

and you should be able to get in.

No Comments

debounce in JavaScript

by Michał Kuklis on 4/06/2011

I ran into a situation recently where a function would get executed repeatedly after given timeout. I wanted to make sure that only last execution was taken into the consideration and I came up with:

function debounce(fn, wait) {
  var timeout = null;
  return function () {
    clearTimeout(timeout);
    var args = arguments;
    var ctx = this;
    timeout = setTimeout(function () {
      fn.apply(ctx, args);
    }, wait);
  }
}

now I can use it like this:

function print(value) {
  console.log(value);
}

var printD = debounce(print, 100);
printD(1);
printD(2);
printD(3);

With this approach only last call will get executed with the value 3.

No Comments

prototype, [[Prototype]], __proto__, constructor in JavaScript

by Michał Kuklis on 7/05/2011

prototype, [[Prototype]], __proto__, constructor can be confusing. Here are a few notes which I’m writting mostly for myself but maybe it will help somebody else:

prototype from the Function point of view:

  • every function has access to a publically available prototype property:
function Foo() {}
console.log(Foo.prototype); //Object
  • the value of the prototype property references a prototype object
  • the prototype object contains an attribute called constructor. The value of the constructor attribute references the function itself when the function is orginally created.
console.log(Foo.prototype.constuctor === Foo); // true

prototype from the object point of view:

  • every object has access to prototype object
  • the prototype is not publicly accessible from the object. The object has an implicit access to the prototype via internal [[Prototype]] property
  • when object is created the value of the [[Prototype]] implicitly references the same object as prototype property of the constructor function
// pseudo code
var foo = new Foo();
foo.[[Prototype]] => Prototype <= Foo.prototype
  • some implementations expose a public attribute on objects called __proto__ which can be used to access prototype object
  • (You should never relay on __proto__ since it’s not a standard. I’m using it here for demo purposes.)

console.log(foo.__proto__ === Foo.prototype) // true
  • it’s important to mention that if the value of the prototype attribute attached to the function changes, the object created before the change happens will still point to the old Prototype object.
Foo.prototype = {};
console.log(foo.__proto__ === Foo.prototype) // false

Here are few more examples which illustrate it:

Please check this exceptional article written by Dmitry A. Soshnikov if you want to learn more about the topic.

No Comments

object literals chaining via prototype in JavaScript

by Michał Kuklis on 27/02/2011

Recently I played with the idea of chaining object literals via prototype. Here is what I came up with:

function chain() {
  var cur = null,
        prev = null;
  for (var i = l = arguments.length - 1; i >= 0; i--) {
    prev = cur;
    cur = (function(params) {
      return function() {
        for (var param in params) {
          this[param] = params[param];
        }
      }
    })(arguments[i]);
    if (i < l) {
      cur.prototype = new prev;
    }
  }
  return new cur;
}

and an example usage:

var a = {a: 1}, b = {b: 2}, c = {c: 3},
var chained = chain(a, b, c);
console.log(chained.c); // 3
No Comments

Creating new objects in JavaScript

by Michał Kuklis on 12/01/2011

I’m writing this to remind myself about what happens when new object is constructed in JavaScript. This is based on the knowledge I have so far. Please let me know if you find something which is not correct.

Every object in JavaScript has a property called [[Prototype]] which is hidden and not accessible. The exceptions are functions which are also objects in JavaScript. Each function has an additional public property called prototype.

This property is used when setting up a prototypal inheritance. It’s important to mention that public prototype property is not equal to the private hidden [[Prototype]] property.

In order to create a new object of the specific type the constructor has to be defined first. In JavaScript constructors are just regular functions. For example:

// function which will be used to construct new object (constructor)
function Foo() {}

A new object can be created with the operator ‘new’:

// new object is created
var foo = new Foo;

The operator ‘new’ in the line above does a few things:

1) it creates a new object with the [[Prototype]] property
2) the [[Prototype]] property of the newly created object is set to the prototype of the function used as a constructor to create the object. This sounds complicated but it’s actually pretty simple. Let’s take a look at this code:

// __proto__ is a visible  
// in some browsers (Chrome, Safari, FF)
// and it's deprecated now: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/proto
// the [[Prototype]] property is set to the prototype of the constructor (function)
console.log(foo.__proto__ === Foo.prototype) // true

3) The newly created object is passed to Foo() as the implicit parameter ‘this’
4) The object ‘this’ is returned and assigned to the variable foo

Foo’s public prototype property is an object itself and has access to it’s own [[Prototype]] property. On top of that it also has an extra property called constructor which points back to function Foo.

We can test it with:

console.log(Foo.prototype.constructor === Foo) // true

Thanks to the prototypal nature of JavaScript we can access the properties of the Foo’s prototype directly from foo. Since we alredy know that:

console.log(foo.__proto__ === Foo.prototype) // true

and:

console.log(Foo.prototype.constructor) // Foo

based on the above we know that:

console.log(foo.constructor === Foo.prototype.constructor) // true

What actually happens when we try to access constructor property from foo is that first the runtime looks up the property on the object foo level and it doesn’t find it:

console.log(foo.hasOwnProperty('constructor')) // false

then it looks up the property in the object referenced by [[Prototype]] property.
Since in this case we know that the [[Prototype]] of foo points to the public prototype property on Foo, the constructor is present and visible.

Here are the tests together:

function Foo() {}
var foo = new Foo;
console.log(Foo.prototype.constructor === Foo) // true
console.log(foo.__proto__ === Foo.prototype) // true
console.log(Foo.prototype.constructor) // Foo
console.log(foo.constructor === Foo.prototype.constructor) // true
console.log(foo.hasOwnProperty('constructor')) // false
No Comments

rendering generic views in rails 3

by Michał Kuklis on 27/09/2010
# serve mustache templates
class TemplatesController < ActionController::Metal
  # include render functionality
  include ActionController::Rendering

  append_view_path Rails.root.join("app", "views")

  def serve
    if env["PATH_INFO"] =~ /^\/templates\/(.+)$/
      key = $1      
      begin
        render :file => "templates/properties/_#{key}.html.mustache"
      rescue    
        self.status = :file_not_found
        self.content_type = 'text/plain'
        self.response_body = ''
      end
    else
      self.status = :file_not_found
      self.content_type = 'text/plain'
      self.response_body = ''
    end
  end
end
No Comments

JavaScript closures

by Michał Kuklis on 25/06/2010

For given content:

  <div id="test0">change me</div>
  <div id="test1">change me</div>
  <div id="test2">change me</div>
  <div id="test3">change me</div>

The code:

 for (var i = 0; i < 4; i++) {
   $('#test' + i).click(function(){
     $(this).html(i);
   });
}

will print (every time any of the elements is clicked):

4
4
4
4

Here is how this could be solved with the closure:

  for (var i = 0; i < 4; i++) {
    (function (i) {
      $('#test' + i).click(function () {
        $(this).html(i);
      });
    })(i);
  }
No Comments