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.