Skip to content
Snippets Groups Projects
hello.rb 1.4 KiB
Newer Older
  • Learn to ignore specific revisions
  • Timothy Kimber's avatar
    Timothy Kimber committed
    #!/usr/bin/env ruby
    
    require 'optparse'
    require 'yaml'
    require 'date'
    
    class Parser
      def self.parse_options(args)
        options = {}
        opt_parser = OptionParser.new do |opts|
          opts.banner = "Greets whoever is identified by data.yml."
          opts.separator "Will use the cowsay program, if it is installed."
          opts.separator "Usage: hello.rb [options]"
          opts.on("-c", "--cow COW", "Show message using cow type COW") do |c|
            options["cow"] = c
          end
          opts.on("-h", "--help", "Prints this help") do
            puts opts
            exit
          end
        end
        opt_parser.parse!(args)
        return options
      end
    end
    
    class Greeting
      def self.greet
        case DateTime.now.hour
        when 0..11
          "Good morning"
        when 12..16
          "Good afternoon"
        else
          "Good evening"
        end
      end
    end
    
    class MaybeCow
      def self.command?(command)
        system("which #{command} > /dev/null 2>&1")
      end
    
      def self.program(options)
        primary = "/usr/games/cowsay"
        alt     = "/usr/bin/tee"
        if command?(primary)
          options["cow"] ? "#{primary} -f #{options["cow"]}" : primary
        else
          alt
        end
      end
    end
    
    options = Parser.parse_options(ARGV)
    data = YAML.load_file('data.yml')
    name = 
      if data["first"]
        "#{data["first"]} #{data["last"]} (#{ENV["USER"]})"
      else
    
    TomiNubi's avatar
    TomiNubi committed
        "fine human being"
    
    Timothy Kimber's avatar
    Timothy Kimber committed
      end
    
    IO.popen(MaybeCow.program(options), "w") do |c|
      c.puts "#{Greeting.greet} #{name}!"
      c.close
      puts
    end