Upgrade to Pro — share decks privately, control downloads, hide ads and more …

December 2011 - Plain Ol' Ruby, Part 3, Logging...

dallasruby
January 03, 2012

December 2011 - Plain Ol' Ruby, Part 3, Logging, Rake, and Command Line Arguments

Barrett Clark continues a mini series on using Ruby without external frameworks. This session builds on the previous while adding logging, rake tasks, and command line arguments.

Source available at: https://github.com/barrettclark/DallasRubyPOR

Barrett can be found on Twitter at http://twitter.com/barrettclark

dallasruby

January 03, 2012
Tweet

More Decks by dallasruby

Other Decks in Programming

Transcript

  1. What’s So Great About Me? • I work at Geoforce

    • I have a Yellow lab • I have this cool sticker on my laptop @barrettclark Tuesday, December 6, 2011
  2. Recap • We create records in a database • Without

    ActiveRecord • We also have tests Tuesday, December 6, 2011
  3. Logs Have Levels • debug • info • warn •

    error • fatal Tuesday, December 6, 2011
  4. Yuck $ grep "puts " * */* Rakefile: puts "Hello

    from rake!" lib/db_connection.rb: puts "Unable to connect to the #{ENV['SCRIPT_ENV']} database" lib/db_connection.rb: puts "Attempting to connect to the #{ENV['SCRIPT_ENV']} database" lib/file_reader.rb: puts "#{zipcode.zip} is #{zipcode.city}, #{zipcode.state}" lib/zipcode.rb: puts "#{sql}\n Tuples: #{result.cmd_tuples}" if ENV['SCRIPT_ENV'] == 'test' lib/zipcode.rb: puts "#{e}: Unable to insert the zipcode: #{@zipcode}" test/zipcode_test.rb: puts 'This does nothing' Tuesday, December 6, 2011
  5. require 'logger' module Logging # This is the magical bit

    that gets mixed into your classes def logger Logging.logger end # Global, memoized, lazy initialized instance of a logger def self.logger @logger ||= Logging.brand_new_logger end protected def self.brand_new_logger if ENV['SCRIPT_ENV'] filename = File.join(File.expand_path(File.dirname(__FILE__)), '..', 'log', ENV['SCRIPT_ENV'] + '.log') Logger.new(filename) else Logger.new(STDOUT) end end end Logger Mixin If we have an environment we will log to that environmental file (like Rails does), otherwise we will log to STDOUT. Tuesday, December 6, 2011
  6. class DBConnection require 'yaml' require 'logging' include Logging attr_reader :conn

    def initialize config = database_config @conn = PGconn.open( :dbname => config['dbname'], :user => config['user'], :port => config['port'] ) rescue logger.error "Unable to connect to the #{ENV['SCRIPT_ENV']} database" end def exec(sql) logger.debug(sql) @conn.exec(sql) end private def database_config logger.debug "Attempting to connect to the #{ENV['SCRIPT_ENV']} database" filename = File.join(File.expand_path(File.dirname(__FILE__)), '..', 'config', 'database.yml') config = YAML.load(File.read(filename)) config[ENV['SCRIPT_ENV'] || 'development'] end end Magic Profit And now we can log queries like you are used to seeing with ActiveRecord! Tuesday, December 6, 2011
  7. Rake tasks $ rake -T (in /Users/barrettclark/Projects/Training/DallasRubyPOR) rake db:truncate #

    Truncate the zipcode table rake default # rake test is the default action. rake log:clear # Clear log files rake test # Run tests rake testing_rake # this is a test Tuesday, December 6, 2011
  8. require 'bundler/setup' Bundler.require -- OR -- $ bundle exec rake

    Rake is just Ruby. Nothing magic about it. * Show the Rakefile * Tuesday, December 6, 2011
  9. def self.help puts <<-TXT \n#{__FILE__} [-t|--truncate] [-h|--help]\n...where... -h or --help

    = show this help message and exit -t or --truncate = truncate the zip_code table first \nIf you wish to just load the file don't enter any command line arguments.\n TXT exit end def self.option_parser ARGV.each do |arg| case arg when '-h', '--help' help when '-t', '--truncate' ZipCode.delete_all else help end end end Sometimes puts is ok Tuesday, December 6, 2011
  10. $ ruby lib/file_reader.rb -h lib/file_reader.rb [-t|--truncate] [-h|--help] ...where... -h or

    --help = show this help message and exit -t or --truncate = truncate the zip_code table first If you wish to just load the file don't enter any command line arguments. Tuesday, December 6, 2011
  11. Better yet... def self.option_parser opts = OptionParser.new opts.on("-t", "--truncate") {

    ZipCode.delete_all } opts.on("-l LEVEL", "--level LEVEL", String) { |level| logger.set_log_level(level) } opts.on("-h", "--help") { puts opts.to_s; exit } opts.parse(ARGV) end $ ruby lib/file_reader.rb -h Usage: file_reader [options] -t, --truncate -l, --level LEVEL -h, --help Tuesday, December 6, 2011