Monday, March 06, 2017

puts_debuggerer v0.5.0 adds caller, formatter, and more goodies

puts_debuggerer v0.5.0

Yes, many of us avoid debuggers like the plague and clamp on to our puts statements like an umbrella in a stormy day. Why not make it official and have puts debugging become its own perfectly legitimate thing?!!
And thus, puts_debuggerer was born. A guilt-free puts debugger Ruby gem FTW!
In other words, puts_debuggerer is a Ruby library for improved puts debugging, automatically displaying bonus useful information such as source line number and source code.
Partially inspired (only partially ;) by this blog post: https://tenderlovemaking.com/2016/02/05/i-am-a-puts-debuggerer.html (Credit to Tenderlove.)
Below are some of its options.

Options

Options enable more data to be displayed with puts_debuggerer, such as the caller backtrace, header, and footer. They also allow customization of output format.

PutsDebuggerer.print_engine

(default = :p)
Print engine to use in object printout (e.g. pappp). It is represented by the print engine's global method name as a symbol (e.g. :ap for awesome_print). Defaults to Ruby's built-in p method identified by the symbol :p. If it finds awesome_print loaded, it defaults to ap as :ap instead.
Example:
# File Name: /Users/User/example.rb
require 'awesome_print'
PutsDebuggerer.print_engine = :ap
array = [1, [2, 3]]
pd array
Prints out:
[PD] /Users/User/example.rb:5
   > pd array
  => [
    [0] 1,
    [1] [
        [0] 2,
        [1] 3
    ]
]

PutsDebuggerer.announcer

(default = "[PD]")
Announcer (e.g. [PD]) to announce every print out with (default: "[PD]")
Example:
PutsDebuggerer.announcer = "*** PD ***\n  "
pd (x=1)
Prints out:
*** PD ***
   /Users/User/example.rb:2
   > pd x=1
  => "1"

PutsDebuggerer.formatter

(default = PutsDebuggerer::FORMATTER_DEFAULT)
Formatter used in every print out Passed a data argument with the following keys:
  • :announcer (string)
  • :caller (array)
  • :file (string)
  • :footer (string)
  • :header (string)
  • :line_number (string)
  • :pd_expression (string)
  • :object (object)
  • :object_printer (proc)
NOTE: data for :object_printer is not a string, yet a proc that must be called to output value. It is a proc as it automatically handles usage of print_engine and encapsulates its details. In any case, data for :object is available should one want to avoid altogether.
Example:
PutsDebuggerer.formatter = -> (data) {
  puts "-<#{data[:announcer]}>-"
  puts "HEADER: #{data[:header]}"
  puts "FILE: #{data[:file]}"
  puts "LINE: #{data[:line_number]}"
  puts "EXPRESSION: #{data[:pd_expression]}"
  print "PRINT OUT: "
  data[:object_printer].call
  puts "CALLER: #{data[:caller].to_a.first}"
  puts "FOOTER: #{data[:footer]}"
}
pd (x=1)
Prints out:
-<[PD]>-
FILE: /Users/User/example.rb
HEADER: ********************************************************************************
LINE: 9
EXPRESSION: x=1
PRINT OUT: 1
CALLER: #/Users/User/master_examples.rb:83:in `block (3 levels) in '
FOOTER: ********************************************************************************

PutsDebuggerer.caller

(default = nil)
Caller backtrace included at the end of every print out Passed an argument of true/false, nil, or depth as an integer.
  • true and -1 means include full caller backtrace
  • false and nil means do not include caller backtrace
  • depth (0-based) means include limited caller backtrace depth
Example:
# File Name: /Users/User/sample_app/lib/sample.rb
PutsDebuggerer.caller = 3
pd (x=1)
Prints out:
[PD] /Users/User/sample_app/lib/sample.rb:3
    > pd x=1
   => "1"
     /Users/User/sample_app/lib/master_samples.rb:368:in \`block (3 levels) in <top (required)>\'
     /Users/User/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/irb/workspace.rb:87:in \`eval\'
     /Users/User/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/irb/workspace.rb:87:in \`evaluate\'
     /Users/User/.rvm/rubies/ruby-2.4.0/lib/ruby/2.4.0/irb/context.rb:381:in \`evaluate\'

Options can be set as a global configuration or piecemeal per puts statement.

Global configuration is done via PutsDebuggerer module attribute writers. On the other hand, piecemeal options can be passed to the pd global method as the second argument.


Example:
# File Name: /Users/User/project/piecemeal.rb
data = [1, [2, 3]]
pd data, header: '>'*80, footer: '<'*80, announcer: "   -<[PD]>-\n  "
Prints out:
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
   -<[PD]>-
   /Users/User/project/piecemeal.rb:3
   > pd data
  => [1, [2, 3]]
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Become a puts_debuggerer!

Sunday, March 05, 2017

puts_debuggerer v0.3.0 (header/footer + multi-line)

What's New in puts_debuggerer v0.3.0 ?

Usage
Simply invoke global pd method anywhere you'd like to see line number and source code with output. If the argument is a pure string, the print out is simplified by not showing duplicate source.
Quickly locate printed lines using Find feature (e.g. CTRL+F) by looking for:
  • [PD]
  • file:line_number
  • ruby expression.
This gives you the added benefit of easily removing your pd statements later on from the code.
Happy puts_debuggerering!
Example Code:
# /Users/User/finance_calculator_app/pd_test.rb # line 1
bug = 'beattle'                                 # line 2
pd "Show me the source of the bug: #{bug}"      # line 3
pd 'What line number am I?'                     # line 4
Example Printout:
[PD] /Users/User/finance_calculator_app/pd_test.rb:3
   > ("Show me the source of the bug: #{bug}").inspect
  => "Show me the source of the bug: beattle"
[PD] /Users/User/finance_calculator_app/pd_test.rb:4 "What line number am I?"

PutsDebuggerer.header

Header to include at the top of every print out.
  • Default value is nil
  • Value true enables header as '*'*80
  • Value falsenil, or empty string disables header
  • Any other string value gets set as a custom header
Example:
PutsDebuggerer.header = true
pd (x=1)
Prints out:
********************************************************************************
[PD] /Users/User/example.rb:2
   > (x=1).inspect
  => "1"

PutsDebuggerer.footer

Footer to include at the bottom of every print out.
  • Default value is nil
  • Value true enables footer as '*'*80
  • Value falsenil, or empty string disables footer
  • Any other string value gets set as a custom footer
Example:
PutsDebuggerer.footer = true
pd (x=1)
Prints out
[PD] /Users/User/example.rb:2
   > (x=1).inspect
  => "1"
********************************************************************************

Become a puts_debuggerer!

Thursday, February 23, 2017

puts_debuggerer

puts_debuggerer

Ruby tools for improved puts debugging, automatically displaying bonus useful information such as file, line number and source code.
Partially inspired by this blog post: https://tenderlovemaking.com/2016/02/05/i-am-a-puts-debuggerer.html (Credit to Tenderlove.)

Instructions

Bundler

Add the following to bundler's Gemfile.
gem 'puts_debuggerer'

Manual

Or manually install and require library.
gem install puts_debuggerer
require 'puts_debuggerer'

Usage

Simple invoke global pd method anywhere you'd like to see line number and source code with output. If the argument is a pure string, the print out is simplified by not showing duplicate source.
Quickly find printed lines by running a find (e.g. CTRL+F) for "pd " or ".inspect => "
Happy puts debugging!
Example Code:
# /Users/User/finance_calculator_app/pd_test.rb # line 1
bug = 'beattle'                                 # line 2
pd "Show me the source of the bug: #{bug}"      # line 3
pd 'What line number am I?'                     # line 4
Example Printout:
pd /Users/User/finance_calculator_app/pd_test.rb:3 "Show me the source of the bug: #{bug}".inspect => "Show me the source of the bug: beattle"
pd /Users/User/finance_calculator_app/pd_test.rb:4 "What line number am I?"

More at puts_debuggerer

Wednesday, February 22, 2017

Ruby's Elegant Way of Dealing with The Array of Hashes vs Single Hash JSON Problem

I'm sure you've encountered REST Web Service APIs that operate as follows:
HTTP Request: =>
GET /people
<= 1 person JSON Response:
{"first_name":"Bob","last_name":"McAndrew","city":"Chicago"}
HTTP Request: =>
GET /people
<= 3 people JSON Response:
[{"first_name":"Bob","last_name":"McAndrew","city":"Chicago"}, {"first_name":"Lisa","last_name":"Donald","city":"Madison"}, {"first_name":"Montgomery","last_name":"Hicks","city":"Indianapolis"}]
How do you work with the varied JSON responses in Ruby?
One approach for an app that needs to count people in cities:
city_counts = {}
json_response = people_http_request
if json_response.is_a?(Hash)
  city_counts[json_response["city"]] ||= 0
  city_counts[json_response["city"] += 1
elsif json_response.is_a?(Array)
  json_response.each do |person|
    city_counts[person["city"]] ||= 0
    city_counts[person["city"]] += 1
  end
end
Not only is the code above redundant and overly complicated, but it also breaks common Ruby and object oriented development standards by relying on explicit type checking instead of duck-typing, polymorphism, or design patterns.
A slightly better version relying on duck-typing would be:
city_counts = {}
json_response = people_http_request
if json_response.respond_to?(:each_pair)
  city_counts[json_response["city"]] ||= 0
  city_counts[json_response["city"] += 1
elsif json_response.respond_to?(:each_index)
  json_response.each do |person|
    city_counts[person["city"]] ||= 0
    city_counts[person["city"]] += 1
  end
end
A slightly clearer version relying on design patterns (Strategy) and parametric polymorphism (functional) would be:
city_counts = {}
city_counting_strategies = {
  Hash: -> { |json_response|
    city_counts[json_response["city"]] ||= 0
    city_counts[json_response["city"] += 1
  },
  Array: -> { |json_response|
    json_response.each do |person|
      city_counts[person["city"]] ||= 0
      city_counts[person["city"]] += 1
    end
  }
}
json_response = people_http_request
city_counting_strategies[json_response.class].call(json_response)
A more radical version relying on object-oriented polymorphism and Ruby open-classes would be:
Hash.class_eval do
  def process_json_response(&processor)
    processor.call(self)
  end
end

Array.class_eval do
  def process_json_response(&processor)
    each(&processor)
  end
end

city_counts = {}
json_response = people_http_request
json_response.process_json_response do |person|
  city_counts[person["city"]] ||= 0
  city_counts[person["city"]] += 1
end
This version is quite elegant, clear, and Ruby idiomatic, but aren't we using a Nuclear device against a fly that sometimes comes as a swarm of flies? I'm sure we can have a much simpler solution, especially in a language like Ruby.
Well, how about this functional solution?
city_counts = {}
[people_http_request].flatten.each do |person|
  city_counts[person["city"]] ||= 0
  city_counts[person["city"]] += 1
end
Yes, hybrid functional/object-oriented programming to the rescue.
One may wonder what to do if the response comes in as nil or includes nil values in an array. Well, this approach can scale to handle that too should ignoring nil be the requirement.
city_counts = {}
[people_http_request].flatten.compact.each do |person|
  city_counts[person["city"]] ||= 0
  city_counts[person["city"]] += 1
end
Can we generalize this elegant solution beyond counting cities? After all, the key problem with the code on top is it gets quite expensive to maintain in a real-world production app containing many integrations with REST Web Service APIs.
This functional generalization should work by allowing you to switch json_response variable and process_json_response proc anyway you want:
[json_response].flatten.compact.each(&:process_json_response)
Example:
[cities_json_response].flatten.compact.each(&:group_by_country)
How about go one step further and bake this into all objects using our previous approach of object-oriented polymorphism and Ruby open-classes? That way, we don't just collapse the difference between dealing with arrays of hashes vs hashes but also arrays of objects vs singular objects by adding. Note the use of flatten(1) below to prevent arrays or arrays from collapsing more than one level.
Object.class_eval do
  def to_collection
    [self].flatten(1).compact
  end
end
Example usage (notice how more readable this is than the explicit version above by hiding flatten and compact):
city_counts = {}
people_http_request.to_collection.each do |person|
  city_counts[person["city"]] ||= 0
  city_counts[person["city"]] += 1
end
A refactored version including optional compacting would be:
Object.class_eval do
  def to_collection(compact=true)
    collection = [self].flatten(1)
    compact ? collection.compact : collection
  end
end
Example usage of to_collection(compact) to count bad person hashes coming as nil:
bad_people_count = 0
city_counts = {}
people_http_request.to_collection(false).each do |person|
  if person.nil?
    bad_people_count += 1
  else
    city_counts[person["city"]] ||= 0
    city_counts[person["city"]] += 1
  end
end
Grab this solution as a Ruby gem: 
https://github.com/AndyObtiva/to_collection


Know of any other solutions to this problem? Please share in comments.