Ruby On Rails : Unknown issue : Function returns unexpected things when I debug/pry

Sometimes when we debug in development or try to log what is happening in production mode, we encounter with some mysterious issues of unexpected value returned by the function/methods. Let us see the scenarios

Scenario 1:

def destroy
  item = get_item
  if item.delete
    flash.now[:notice] = 'Successfully deleted'
  end
end
private
def get_item
  Item.find(params[:id])
end

Scenario 2 :

def destroy
  item = get_item
  if item.delete
    flash.now[:notice] = 'Successfully deleted'
  end
end
private
def get_item
  Item.find(params[:id])
  # To pry the value, used binding.pry or logger.into 'inside get_item'
  binding.pry
  # logger.into 'inside get_item'
end

Findings:  In scenario 1, every thing is alright however, scenario 2 is error prone, error such as ‘NoMethodError: Undefined method `delete for “item”‘ is expected to arise.

This is because, whenever ruby interpreter executes the method ‘get_item‘ it finds ‘binding.pry‘ which initiates new ‘irb‘ session and on ‘exit‘ the ‘binding.pry‘ returns ‘false‘. This false is now returned by the method ‘get_item‘. In case of ‘logger.info or logger.error‘ the method ‘get_item‘ returns what the ‘logger.error‘ returns.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s