Avatar

This is a rake task that will pretty print the HTTP status codes and their named symbol variants as used in Rails.
You can either list all of them with "$ rake status_codes" or drill down with a specific code or match.
Match all codes starting with "42": $ rake status_code code=42
Match all named codes starting with "re": $ rake status_code code=re

Especially the longest_name line could be a good candidate for refactoring (maybe some stdlib lib?).

1
2
3
4
5
6
7
8
desc 'Prints out the status codes and their named symbols. Limit by specifying `code=`, with one or more digits or with the start of a named code.'
task :status_codes do
  require 'action_controller/status_codes'
  include ActionController::StatusCodes
  
  longest_symbol = SYMBOL_TO_STATUS_CODE.map { |code, _| code.to_s.length }.max
  puts STATUS_CODES.keys.sort.map { |code| "#{code}  :#{SYMBOL_TO_STATUS_CODE.index(code)}  #{STATUS_CODES[code].rjust(longest_symbol)}" }.grep(/(^|:)#{ENV['CODE'] || ENV['code']}/i)
end

Refactorings

No refactoring yet !

Avatar

alloy

August 29, 2008, August 29, 2008 09:34, permalink

No rating. Login to rate!

Oh and short but still readable is the objective.
This is a rake task, so much is allowed imo. As in, it doesn't need to be the cleanest code ever.

Avatar

alloy

August 29, 2008, August 29, 2008 10:30, permalink

No rating. Login to rate!

Ok for fun, but not really an improvement:

1
2
3
4
5
6
desc 'Prints out the status codes and their named symbols. Limit by specifying `code=`, with one or more digits or with the start of a named code.'
task :status_codes do
  lib = 'ActionController::StatusCodes'; require lib.underscore and include lib.constantize
  longest_symbol = SYMBOL_TO_STATUS_CODE.map { |code, _| code.to_s.length }.max
  puts STATUS_CODES.keys.sort.map { |code| "#{code}  :#{SYMBOL_TO_STATUS_CODE.index(code)}  #{STATUS_CODES[code].rjust(longest_symbol)}" }.grep(/(^|:)#{ENV['CODE'] || ENV['code']}/i)
end
A8d3f35baafdaea851914b17dae9e1fc

Adam

September 3, 2008, September 03, 2008 05:14, permalink

No rating. Login to rate!
1
2
3
4
5
6
7
8
task :status_codes do
  require 'action_controller/status_codes'
  include ActionController::StatusCodes  
  
  SYMBOL_TO_STATUS_CODE.sort_by(&:last).map do |symbol,status|    
    "%-4s :%-32s %s\n" % [ status, symbol, STATUS_CODES[status] ]
  end.grep(/(^|:)#{ENV['CODE'] || ENV['code']}/i).display
end

Your refactoring





Format Copy from initial code

or Cancel