Debugging: What is binding in Ruby?

You might have thought always whenever you wrote code binding.pry in your application to debug your application.

People often say “do binding to see whats going on”. Actually you are not doing binding but prying into the binding. So, its good to say “Please pry into that binding”.

But, what is binding in the first place? Continue reading

Advertisements

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.