Usage of Closure in Javascript

In this article you are going to see what you can do with the power of Closure in Javascript. This not an article about what Closure is. This is an article about what Closure can do. I see a lot of people asking the question what’s the big deal with Closure. They want more real world cases where Closure will make sense.

Example 1: Getting digit name

The goal is to read from an array and display the result. The first implementation is to put everything in Global namespace.

var names = ['zero', 'one', 'two', 'three', 'four', 'five'];

var digit_name = function(n) {
  return names[n];
};

alert(digit_name(3)); // 'three'

Above solution works. However creating a global variable names is not a good thing. You should create as less global variables as possible.

Moving to a function

Next step is to move the code to a function. In this case we will not have any global variable.

var digit_name = function(n){
  var names = ['zero', 'one', 'two', 'three', 'four', 'five'];
  return names[n];
};
alert(digit_name(3));

The above solution is very slow. Every single time the function is called the whole array is loaded. This solution works and most of the developers will settle with this one. However Closure can provide a better solution.

Better solution with Closure

var digit_name = function(){
  var names = ['zero', 'one', 'two', 'three', 'four', 'five'];

  return function(n){
    return names[n];
  };
}();
alert(digit_name(3));

Note that at after declaring the function the function is also getting invoked. This is a case of self invoking function. You can find out more about self invoking function here .

Example 2: Getters and Setters

Developers deal with getters and setters all the time. However creating a good getter and setter could be a little tricky. Here is one implementation

function Field(val){
    var value = val;

    this.getValue = function(){
        return value;
    };

    this.setValue = function(val){
        value = val;
    };
}

var field = new Field("test");
field.value
// => undefined
field.setValue("test2")
field.getValue()
// => "test2"

Above solution works and it’s nicely done.

Let’s look at another implementation.

var getValue, setValue;
(function() {
  var secret = 0;
  getValue = function(){
    return secret;
  };
  setValue = function(v){
    secret = v;
  };
})()

setValue('foo');
getValue(); // foo

Example 3: Building an iterator using Javascript

function custome_iterator(x) {
  var i = 0;
  return function(){
    return x[i++];
  };
}

var next = setup(['one', 'two', 'three', 'four']);

next();
next();
next();

This is a simple case of serially iterating through the items provided but the logic of deciding next element can be complex and it can be private.

Closure is a big topic and a lot of people have written a lot about it. Just search for Closure and you will get tons of links. I refer to this article time to time to see what pattern to use to make best usage of Javascript Closure.

This article was inspired by this book, this video and this article .

Understanding jQuery Plugin Pattern and self-invoking javascript function

I am learning jQuery and one of things I was struggling with is the plugin pattern. In jQuery world it is very common to wrap the major functionality of the application inside a plugin.

Here is a great article which describes in detail how to wrap your javascript code inside a jQuery plugin. The article did a great job of explaining the basics however it took me a while to understand the self-invoking functions.

Self-invoking functions

self-invoking functions are anonymous functions declared on run time and then invoke it right then and there. Since they are anonymous functions they can’t be invoked twice. However they are a good candidate for initialization work which is exactly what is happening in the jQuery plugin pattern.

Declaring a function

A function can be declared in two ways:

function hello(){ alert('Hello');}
var hello = function(){ alert('Hello'); }

The end result in the above two javascript statement was same. In the end a variable named hello was created which is a function.

Please note that in the above case only the functions are declared. They are not invoked. In order to invoke the function we have to do this

var hello = function(){ alert('Hello'); }
hello();

How do we invoke an anonymous function. We need to call () on the anonymous function. But before that we need to wrap the whole command in (). Take a look at this

// original
function hello(){ alert('Hello');}

// step1 wrap everything in () so that we have a context to invoke
(function hello(){ alert('Hello');})

// now call () to invoke this function
(function hello(){ alert('Hello');})();

The final result is weird looking code but it works and that is how an anonymous function is declared and invoke on run time.

With this understanding now it becomes easier to see what is happening in this code

(function($) {
  // ....
})(jQuery);

In the above case an anonymous function is being created. However unlike my anonymous function this anonymous function take a parameter and the name of this paramter is $. $ is nothing else but jQuery object that is being passed while invoking this function.

How to find if my commits are executed in a transaction or not

ActiveRecord::Base.connection.supports_ddl_transactions?

Restful architecture does not mean one to one mapping with model

Rails makes it easy to adapt Restful architecture. All you have to do is

map.resources :pictures

I started putting all pictures related activities in pictures_controller.rb . In the beginning it was simple.

Slowly the application evolved. The application started handling two different types of pictures. There would be pictures for events and then there would be pictures of users using the system.

You can add comments to the event pictures but you can’t add comment to user pictures. And slowly the requirement for event pictures grew vastly different from user pictures.

Sounds familiar. Right. Initially controller takes on a few responsibilities but slowly the controller starts taking a lot more responsibilities and then controller becomes huge in code size.

The pictures controller was really really huge and was fast becoming a mess. Especially writing test was getting very difficult.

Time had come to create two different controllers: one for event pictures and one for user pictures.

But wait. Lots of people would say that if we want to be restful then there has to be one to one mapping between the model and the controller. Not true.

Model != resource

Being restful does not mean that there has be a one to one mapping between the model and the controller.

I am going to create a new controller called user_pictures_controller.rb that will take on all the functionality related to users dealing with picture. And this is going to be restful.

map.resources :user_pictures

Above I have defined a resource called user_pictures. To keep it simple this controller would do only three things.

  • display all the pictures of the user ( index )
  • allow user to upload pictures ( create )
  • allow user to delete a picture ( destroy )

That’s the general idea. In my application I have only three actions.

However in the interest of general discussion I am going to show all the seven methods here. Also for simplicity create in this case means adding a record (I am not showing multipart upload).

Controller

Here is the code for controller.

# user_pictures_controller.rb

class UserPicturesController < ApplicationController

  def index
    @pictures = Picture.all
  end

  def new
    render
  end

  def create
    @picture = Picture.new(params[:picture])
    if @picture.save
      flash[:notice] = 'Picture was successfully created.'
      redirect_to user_picture_path(:id => @picture.id)
    else
      render :action => "new"
    end
  end

  def show
    @picture = Picture.find(params[:id])
  end

  def edit
    @picture = Picture.find(params[:id])
  end

  def update
    @picture = Picture.find(params[:id])
    if @picture.update_attributes(params[:picture])
      flash[:notice] = 'Picture was successfully updated.'
      redirect_to user_picture_path(:id => @picture.id)
    else
      render :action => "edit"
    end
  end

  def destroy
    @picture = Picture.find(params[:id])
    @picture.destroy

    redirect_to user_pictures_path
  end

end

View

# index.html.erb
<h1>Listing pictures</h1>

<table>
  <tr>
    <th>Name</th>
    <th>Quality</th>
  </tr>

<% for picture in @pictures %>
  <tr>
    <td><%=h picture.name %></td>
    <td><%=h picture.quality %></td>
    <td><%= link_to 'Show', user_picture_path(picture) %></td>
    <td><%= link_to 'Edit', edit_user_picture_path(picture) %></td>
    <td>  <%= link_to 'Destroy',  user_picture_path(picture),
                                :confirm => 'Are you sure?',
                                :method => :delete %>

    </td>
  </tr>
<% end %>
</table>


<%= link_to 'New picture', new_user_picture_path %>
# edit.html.erb
<h1>Editing picture</h1>

<% form_for(:picture,
            :url => user_picture_path(@picture),
            :html => {:method => :put}) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :quality %><br />
    <%= f.text_field :quality %>
  </p>
  <p>
    <%= f.submit "Update" %>
  </p>
<% end %>

<%= link_to 'Show', user_picture_path(@picture) %> |
<%= link_to 'All', user_pictures_path %>
# new.html.erb
<h1>New picture</h1>

<% form_for(:picture, :url => user_pictures_path, :html => {:method => :post}) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :quality %><br />
    <%= f.text_field :quality %>
  </p>
  <p>
    <%= f.submit "Create" %>
  </p>
<% end %>

<%= link_to 'All', user_pictures_path %>
# show.html.erb
<p>
  <b>Name:</b>
  <%=h @picture.name %>
</p>

<p>
  <b>Quality:</b>
  <%=h @picture.quality %>
</p>

<%= link_to 'Edit', edit_user_picture_path(:id => @picture) %> |
<%= link_to 'All', user_pictures_path %>

Another use case

Let’s talk about another example. Let’s say that we have a model called project and besides the regular functionality of creating, deleting, updating and listing projects, one needs two more actions called enable and disable project.

Well the projects controller can easily handle two more actions called enable and disable. However it is a good idea to create another controller called project_status_controller . And this controller should have only two actions - create and destroy. destroy in this case would mean disabling the project and create would mean enabling the controller. I know initially it looks counter intuitive. Why would you know have actions called ‘enable’ and ‘disable’ which are much more easy to relate to compared to having another controller with methods ‘create’ and ‘destroy’. All I can say is that REST is a big topic. Do a search on REST and try reading a few books. Also the more you work developing RESTful controller the more you will understand about it.

Conclusion

In this blog I tried to show that it is not necessary to have one to one mapping between model and controllers to be restful.

It is always a good idea to create a separate controller when the existing controller is burdened with too much work.

rescue_action_in_public, local_request? and how to configure local_request

How does Rails handle exceptions ?

Rails exception handling depends on two factors and we are going to discuss both of them here.

# ~/lib/action_controller/rescue.rb
if consider_all_requests_local || local_request?
  rescue_action_locally(exception)
else
  rescue_action_in_public(exception)
end

When exceptions are handled by rescue_action_locally then we get to see the page with stacktrace. When exceptions are handled by rescue_action_in_public, we get to see the public/500.html or an error page matching the error code.

As you can see Rails uses two different methods consider_all_requests_local and local_request? to decide how exception should be handled.

Method consider_all_requests_local

consider_all_requests_local is a class level variable for ActionController::Base . We hardly pay attention to it but it is configured through files residing in config/environments

# config/environments/development.rb
config.action_controller.consider_all_requests_local = true

# config/environments/production.rb
config.action_controller.consider_all_requests_local = false

As you can see in development environment all the requests are considered local.

I have overridden the method local_request? but I am still not able to see public page when exception is raised.

That is a common question I see in the mailing list. As you can see the condition to decide how to handle exception is

if consider_all_requests_local || local_request?

In development environment consider_all_requests_local is always true as I showed before. Since one of the conditions is true Rails always handles the exception using rescue_action_locally .

I am running in production mode but I am still not able to see public/500.html page when I get exception at http://localhost:3000.

Same issue. In this case you are running in production mode so consider_all_requests_local is false but local_request? is still true because of localhost.

I want local_request? to be environment dependent

Recently I started using hoptoad and I needed to test how hoptoad will handle exception in production mode. However without any change local_request? was always returning true for http://localhost:30000 .

Then I stick following file under config/initializers

# config/initializers/local_request_override.rb
module CustomRescue
  def local_request?
    return false if Rails.env.production? || Rails.env.staging?
    super
  end
end

ActionController::Base.class_eval do
  include CustomRescue
end

Now all request in production or in staging mode are treated as NOT local.

Now in both staging and production mode I get to see 500.html page even if I am accessing the application from http://localhost:3000 .

Override automatic updated_at in ActiveRecord/Rails

Rails provides some good tools like automatically updating created_at and updated_at columns. Developers do not need to worry about these columns. Rails updates these columns automatically which is great. Click here to find out how rails does auto time stamping.

However I have a unique business need where I need to update a column but I do not want updated_at to be changed. Or we can see the problem this way. I want to change the updated_at to a particular value.

>> User.first.update_attributes(:updated_at => 100.years.ago)
UPDATE `users` SET `updated_at` = '2009-01-20 19:15:25' WHERE `id` = 2

Look at the sql that is generated. Rails discarded the updated_at value that I had supplied and replaced the value by the current time. Rails works fine if you supply created_at value. It is the updated_at value that is discarded.

Rails provides a feature called ActiveRecord::Base.record_timestamps . Using this feature I can tell rails to not to auto time stamp records.

Let’s try that.

>> User.record_timestamps=false
=> false
>> User.first.update_attributes(:updated_at => 100.years.ago)
UPDATE `users` SET `updated_at` = '1909-01-20 18:52:50' WHERE `id` = 2
>> User.record_timestamps=true
=> true

It worked. I have successfully set updated_at to year 1909. However there is a problem.

For a brief duration User.record_timestamps was set to false. That is a class level variable. It means that for that brief duration if any other User record is updated then that record will not have correct updated_at value. That is not right. I want just one record ( User.first) to not to change updated_at without changing the behavior for the whole application.

In order to isolate the behavior to only the record we are interested in, I can do this.

>> u = User.first

>> class << u
>>  def record_timestamps
>>    false
>>  end
>> end

>> u.update_attributes(:updated_at => 100.years.ago)
UPDATE `users` SET `updated_at` = '1909-01-20 18:58:10' WHERE `id` = 2

>> class << u
>>  def record_timestamps
>>    super
>>  end
>> end

>> u.update_attributes(:updated_at => 200.years.ago)
UPDATE `users` SET `updated_at` = '2009-01-20 19:22:11' WHERE `id` = 2

In order to restrict the changes to a model, I am opening up the metaclass of u ( user object) and in that object I am adding a method called record_timestamps . The idea is to insert a method called record_timestamps in the metaclass which will return true and in this way the changes are restricted to a single object rather than making change at the class level.

At this point the meta class of the user object has the method record_timestamps and this returns false. Now I update the record with updated_at set to 100 years ago. And I succeed.

Now I need to put the object behavior back to normal. I open up the metaclass and call super on the method so that the method call will go up the chain. And that’s what happens when I try to test updated_at. This time the updated_at value that I set is ignored and rails changes the updated_at value.

update_without_timestamping method

This strategy of opening up an instance object works but it is messy. I would like to have a method that is much easier to use and this is what I came up with. Stick this piece of code in an initializer.

module ActiveRecord
  class Base

    def update_record_without_timestamping
      class << self
        def record_timestamps; false; end
      end

      save!

      class << self
        def record_timestamps; super ; end
      end
    end

  end
end

This is how you can use it.

>> u = User.first
>> u.updated_at = 100.years.ago
>> u.created_at = 200.years.ago
>> u.update_record_without_timestamping
UPDATE `users` SET `created_at` = '1809-01-20 19:08:21',
`updated_at` = '1909-01-20 19:08:22' WHERE `id` = 2

Good usage of remove_method

In the above solution I used super when I want to bring back the default auto time stamping behavior. In stead of super I can also use remove_method. More about the what remove_method does is here .

module ActiveRecord
  class Base

    def update_record_without_timestamping
      class << self
        def record_timestamps; false; end
      end

      save!

      class << self
        remove_method :record_timestamps
      end
    end

  end
end

Using the above technique, I can fully control updated_at values without rails messing up anything.

Under the hood how named_scope works

Following code was tested with ruby 1.8.7 and Rails 2.x .

Rails recently added named_scope feature and it is a wonderful thing. If you don’t know what named_scope is then you can find out more about it here and here .

This article is not about how to use named_scope. This article is about how named_scope does what it does so well.

Understanding with_scope

ActiveRecord has something called with_scope which is not associated with named_scope. The two are entirely separate thing. However named_scope relies on the workings on with_scope to do its magic. So in order to understand how named_scope works first let’s try to understand what with_scope is.

with_scope let’s you add scope to a model in a very extensible manner.

def self.all_male
  with_scope(:find => {:conditions => "gender = 'm'"}) do
    all_active
  end
end

def self.all_active
  with_scope(:find => {:conditions => "status = 'active'"}) do
    find(:first)
  end
end

# User.all_active
# SELECT * FROM "users" WHERE (status = 'active') LIMIT 1

# User.all_male
# SELECT * FROM "users" WHERE ((gender = 'm') AND (status = 'active')) LIMIT 1

We can see that when User.all_male is called, it internally calls all_active method and the final sql has both the conditions.

with_scope allows nesting and all the conditions nested together are used to form one single query. And named_scope uses this feature of with_scope to form one single query from a lot of named scopes.

Writing our own named_scope called mynamed_scope

The best way to learn named_scope is by implementing the functionality of named_scope ourselves. We will build this functionality incrementally. To avoid any confusion we will call our implementation mynamed_scope.

To keep it simple in the first iteration we will not support any lambda operation. We will support simple conditions feature. Here is a usage of mynamed_scope .

class User < ActiveRecord::Base
  mynamed_scope :active, :conditions => {:status =>  'active'}
  mynamed_scope :male, :conditions => {:gender => 'm'}
end

We expect following queries to provide right result.

User.active
User.male
User.active.male
User.male.active

Let’s implement mynamed_scope

At the top of user.rb add the following lines of code

module ActiveRecord
  module MynamedScope
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def mynamed_scope(name,options = {})
        puts "name is #{name}"
      end
    end

  end
end
ActiveRecord::Base.send(:include, ActiveRecord::MynamedScope)

Now in script/console if we do User then the code will not blow up.

Next we need to implement functionalities so that mynamed_scope creates class methods like active and male.

What we need is a class where each mynamed_scope could be stored. If 7 mynamed_scopes are defined on User then we should have a way to get reference to all those mynamed_scopes. We are going to add class level attribute myscopes which will store all the mynamed_scopes defined for that class.

def myscopes
  read_inheritable_attribute(:myscopes) || write_inheritable_attribute(:myscopes, {})
end

This discussion is going to be tricky.

We are storing all mynamed_scope information in a variable called myscopes. This will contain all the mynamed_scopes defined on User.

However we need one more way to track the scoping. When we are executing User.active then the active mynamed_scope should be invoked on the User. However when we perform User.male.active then the mynamed_scope active should be performed in the scope of User.male and not directly on User.

This is really crucial. Let’s try one more time. In the case of User.active the condition that was supplied while defining the mynamed_scope active should be acted on User directly. However in the case of User.male.active the condition that was supplied while defining mynamed_scope active should be applied on the scope that was returned by User.male .

So we need a class which will store proxy_scope and proxy_options.

class Scope
  attr_reader :proxy_scope, :proxy_options
  def initialize(proxy_scope, options)
    @proxy_scope, @proxy_options = proxy_scope, options
  end
end # end of class Scope

Now the question is when do we create an instance of Scope class. The instance must be created at run time. When we execute User.male.active, until the run time we don’t know the scope object active has to work upon. It means that User.male should return a scope and on that scope active will work upon.

So for User.male the proxy_scope is the User class. But for User.male.active, mynamed_scope ‘active’ gets (User.male) as the proxy_scope.

Also notice that proxy_scope happens to be the value of self.

Base on all that information we can now write the implementation of mynamed_scope like this.

def mynamed_scope(name,options = {})
  name = name.to_sym
  myscopes[name] = lambda { |proxy_scope| Scope.new(proxy_scope,options) }

  (class << self; self end).instance_eval do
    define_method name do
      myscopes[name].call(self)
    end
  end
end

At this point of time the overall code looks like this.

module ActiveRecord
  module MynamedScope
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods

      def myscopes
        read_inheritable_attribute(:myscopes) || write_inheritable_attribute(:myscopes, {})
      end

      def mynamed_scope(name,options = {})
        name = name.to_sym
        myscopes[name] = lambda { |proxy_scope| Scope.new(proxy_scope,options) }

        (class << self; self end).instance_eval do
          define_method name do
            myscopes[name].call(self)
          end
        end
      end

      class Scope
        attr_reader :proxy_scope, :proxy_options
        def initialize(proxy_scope, options)
          @proxy_scope, @proxy_options = proxy_scope, options
        end
      end # end of class Scope

    end # end of module ClassMethods

  end # endof module MynamedScope
end
ActiveRecord::Base.send(:include, ActiveRecord::MynamedScope)


class User < ActiveRecord::Base
  mynamed_scope :active, :conditions => {:status =>  'active'}
  mynamed_scope :male, :conditions => {:gender => 'm'}
end

On script/console

>> User.active.inspect
  SQL (0.000549)    SELECT name
 FROM sqlite_master
 WHERE type = 'table' AND NOT name = 'sqlite_sequence'

=> "#<ActiveRecord::MynamedScope::ClassMethods::Scope:0x203201c @proxy_scope=User(id: integer, gender: string, status: string, created_at: datetime, updated_at: datetime), @proxy_options={:conditions=>{:status=>"active"}}>"
>>

What we get is an instance of Scope. What we need is a way to call sql statement at this point of time.

But calling sql can be tricky. Remember each scope has a reference to the proxy_scope before it. This is the way all the scopes are chained together.

What we need to do is to start walking through the scope graph and if the previous proxy_scope is an instance of scope then add the condition from the scope to with_scope and then go to the previous proxy_scope. Keep walking and keep nesting the with_scope condition until we find the end of chain when proxy_scope will NOT be an instance of Scope but it will be a sub class of ActiveRecord::Base.

One way of finding if it is an scope or not is to see if it responds to find(:all). If the proxy_scope does not respond to find(:all) then keep going back because in the end User will be able to respond to find(:all) method.

# all these two methods to Scope class
def inspect
  load_found
end

def load_found
  find(:all)
end

Now in script/console you will get undefined method find. That is because find is not implemented by Scope.

Let’s implement method_missing.

def method_missing(method, *args, &block)
  if proxy_scope.myscopes.include?(method)
    proxy_scope.myscopes[method].call(self)
  else
    with_scope :find => proxy_options do
      proxy_scope.send(method,*args)
    end
  end
end

Statement User.active.male invokes method ‘male’ and since method ‘male’ is not implemented by Scope, we don’t want to call proxy_scope yet since this method ‘male’ might be a mynamed_scope. Hence in the above code a check is done to see if the method that is missing is a declared mynamed_scope or not. If it is not a mynamed_scope then the call is sent to proxy_scope for execution. Pay attention to with_scope. Because of this with_scope all calls to proxy_scope are nested.

However Scope class doesn’t implement with_scope method. However the first proxy_scope ,which will be User in our case, implements with_scope method. So we can delegate with_scope method to proxy_scope like this.

delegate :with_scope,  :to => :proxy_scope

At this point of time the code looks like this

module ActiveRecord
  module MynamedScope
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods

      def myscopes
        read_inheritable_attribute(:myscopes) || write_inheritable_attribute(:myscopes, {})
      end

      def mynamed_scope(name,options = {})
        name = name.to_sym
        myscopes[name] = lambda { |proxy_scope| Scope.new(proxy_scope,options) }

        (class << self; self end).instance_eval do
          define_method name do
            myscopes[name].call(self)
          end
        end
      end

      class Scope
        attr_reader :proxy_scope, :proxy_options
        delegate :with_scope,  :to => :proxy_scope
        def initialize(proxy_scope, options)
          @proxy_scope, @proxy_options = proxy_scope, options
        end

        def inspect
          load_found
        end

        def load_found
          find(:all)
        end

        def method_missing(method, *args, &block)
          if proxy_scope.myscopes.include?(method)
            proxy_scope.myscopes[method].call(self)
          else
            with_scope :find => proxy_options do
              proxy_scope.send(method,*args)
            end
          end
        end

      end # end of class Scope

    end # end of module ClassMethods

  end # endof module MynamedScope
end
ActiveRecord::Base.send(:include, ActiveRecord::MynamedScope)


class User < ActiveRecord::Base
  mynamed_scope :active, :conditions => {:status =>  'active'}
  mynamed_scope :male, :conditions => {:gender => 'm'}
end

Let’s checkout the result in script/console

>> User.active
SELECT * FROM "users" WHERE ("users"."status" = 'active')
>> User.male
SELECT * FROM "users" WHERE ("users"."gender" = 'm')
>> User.active.male
SELECT * FROM "users" WHERE (("users"."gender" = 'm') AND ("users"."status" = 'active'))
>> User.male.active
SELECT * FROM "users" WHERE (("users"."status" = 'active') AND ("users"."gender" = 'm'))

# you can also see count
>> User.active.count
SELECT count(*) AS count_all FROM "users" WHERE ("users"."status" = 'active')
=> 2

named_scope supports a lot more things than what we have shown. named_scope supports passing lambda instead of conditions and it also supports joins and extensions.

However in the process of building mynamed_scope we got to see the workings of the named_scope implementation.

Why the id of nil is 4 in Ruby

Following code was tested with ruby 1.8.7 and Rails 2.3 .

While developing rails application you have must seen this

Called id for nil, which would mistakenly be 4 — if you really
wanted the id of nil, use object_id

We all know that this message is added by Rails and it is called whiny nil . If you open your config/development.rb file you will see

# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true

Simply stated it means that if the application happens to invoke id on a nil object then throw an error. Rails assumes that under no circumstance a developer wants to find id of a nil object. So this must be an error case and Rails throws an exception.

The question I have is why 4. Why Matz chose the id of nil to be 4. This awesome presentation on ‘Ruby Internals’ has the answer.

In short Matz decided to have all the odd numbers reserved for numerical values. Check this out.

> irb
>> 0.id
(irb):1: warning: Object#id will be deprecated; use Object#object_id
=> 1
>> 1.id
(irb):2: warning: Object#id will be deprecated; use Object#object_id
=> 3
>> 2.id
(irb):3: warning: Object#id will be deprecated; use Object#object_id
=> 5
>> 3.id
(irb):4: warning: Object#id will be deprecated; use Object#object_id
=> 7

Id 1,3,5 and 7 are taken by 0,1,2 and 3.

Now we are left with the id 0,2,4 and higher values.

> irb
> FALSE.id
(irb):5: warning: Object#id will be deprecated; use Object#object_id
=> 0
>> TRUE.id
(irb):6: warning: Object#id will be deprecated; use Object#object_id
=> 2

FALSE had the id 0 and TRUE has the id 2.

Now the next available id left is 4 and that is taken by NIL.

> irb
>> NIL.id
(irb):7: warning: Object#id will be deprecated; use Object#object_id
=> 4

We won’t even be discussing this issue once 1.9 comes out where we will have to use object_id and then this won’t be an issue.

You can follow more discussion about this article at Hacker news .

Legacy Robot Framework

<!DOCTYPE html>

Redirecting…

Redirecting…

Click here if you are not redirected.

Legacy React Native

<!DOCTYPE html>

Redirecting…

Redirecting…

Click here if you are not redirected.

Legacy Rails 5

<!DOCTYPE html>

Redirecting…

Redirecting…

Click here if you are not redirected.

Legacy Delayed Job

<!DOCTYPE html>

Redirecting…

Redirecting…

Click here if you are not redirected.