Forum: Ruby cat2rafb (#77)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-04-28 17:28
(Received via mailing list)
The three rules of Ruby Quiz:

1.  Please do not post any solutions or spoiler discussion for this quiz
until
48 hours have passed from the time on this message.

2.  Support Ruby Quiz by submitting ideas as often as you can:

http://www.rubyquiz.com/

3.  Enjoy!

Suggestion:  A [QUIZ] in the subject of emails about the problem helps
everyone
on Ruby Talk follow the discussion.  Please reply to the original quiz
message,
if you can.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

by Sean Carley

The goal of cat2rafb is to implement a command line utility that will
allow you
to submit arbitrary text to http://rafb.net/paste/ and get the URL for
the text
back.  Bonus points for pushing the URL through http://rubyurl.com/ to
make it
more manageable.

cat2rafb could work like cat, taking files as input or text until ^D
after
entering the command.
4d7bf65b4675b3e9575617929ab123f1?d=identicon&s=25 Paul Novak (Guest)
on 2006-04-28 17:34
(Received via mailing list)
And we should submit our solutions to rafb (after the spoiler period),
as well as to the list?

Nice self-referential touch!

Regards,

Paul.
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-04-28 17:47
(Received via mailing list)
On Apr 28, 2006, at 10:34 AM, Paul Novak wrote:

> And we should submit our solutions to rafb (after the spoiler period),
> as well as to the list?

As long as they make it here, I'm happy.  :)

James Edward Gray II
893c38bd5f182afc751540657d8aacf7?d=identicon&s=25 Stefano Taschini (Guest)
on 2006-05-03 18:56
(Received via mailing list)
#!/usr/bin/env ruby

require 'optparse'
require 'net/http'

# Command-Line Interface.
class Cli

  Languages = %w{C89 C C++ C# Java Pascal Perl PHP PL/I Python Ruby
SQL VB Plain\ Text}
  Aliases = {"c99" => "C", "visual basic" => "VB", "text" => "Plain
Text"}
  PasteUrl = "http://rafb.net/paste/paste.php"

  attr :parser
  attr :opt

  # Initialize the command-line parser and set default values for the
  # options.
  def initialize
    @opt = {
      :lang => "Plain Text",
      :nick => "",
      :desc => "",
      :tabs => "No",
      :help => false}
    @parser = OptionParser.new do |cli|
      cli.banner += " [file ...]"
      cli.on('-l','--lang=L', 'select language') { |s|
        l = s.downcase
        opt[:lang] =
        if Aliases.include?(l) then
          Aliases[l]
        else
          Languages.find(proc{ raise OptionParser::InvalidArgument,l
}) { |x| x.downcase == l}
        end
      }
      cli.on('-n', '--nick=NAME', 'use NAME as nickname') { |s|
opt[:nick] = s}
      cli.on('-d', '--desc=TEXT', 'use TEXT as description') { |s|
opt[:desc] << s }
      cli.on(      '--tabs=N', Integer, 'expand tabs to N blanks (N >=
0)') {|n|
        raise OptionParser::InvalidArgument, n unless n>=0
        opt[:tabs] = n
      }
      cli.on('-h', '--help', 'show this information and quit') {
opt[:help] = true }
      cli.separator ""
      cli.separator "Languages (case insensitive):"
      cli.separator "
"+(Languages+Aliases.keys).map{|x|x.downcase}.sort.join(",")
    end
  end

  # Post the given text with the current options to the given uri and
  # return the uri for the posted text.
  def paste(uri, text)
    response = Net::HTTP.post_form(
      uri,
      { "lang" => opt[:lang],
        "nick" => opt[:nick],
        "desc" => opt[:desc],
        "cvt_tabs" => opt[:tabs],
        "text" => text,
        "submit" => "Paste" })
    uri.merge response['location'] || raise("No URL returned by
server.")
  end

  # Parse the command-line and post the content of the input files to
  # PasteUrl.  Standard input is used if no input files are specified
  # or whenever a single dash is specified as input file.
  def run
    parser.parse!(ARGV)
    if opt[:help]
      puts parser.help
    else
      puts paste(URI.parse(PasteUrl), ARGF.read)
    end
  rescue OptionParser::ParseError => error
    puts error
    puts parser.help()
  end

end

if __FILE__ == $0
  Cli.new.run
end

=begin rdoc

:section: A few remarks

The part of this script that actually deals with the http service is
rather short, entirely contained in Cli#paste.

Most of the code sets up the command-line interface so that the user
can specify options such as a nickname, a description, tab expansion,
and the language used for (a rather discreet) syntax highlihting.

A summary of the command-line syntax can be obtained by typing

 cat2rafb --help

on the command line or by

 require 'cat2rafb'
 cli = Cli.new;
 puts cli.parser.help

in ruby.

=end
A9b6a93b860020caf9d2d1d58c32478f?d=identicon&s=25 Ross Bamford (Guest)
on 2006-05-03 18:56
(Received via mailing list)
My solution is attached (It's also at http://rubyurl.com/mgX but I know
these messages are archived so I included it here). It's a pretty short
thing and not the cleanest code but this was one of those 'just get it
written' things for me :)

Synopsis:
  cat2rafb.rb [-nNickname] [-dDesc] [-lLanguage] [-cConvtabs] [-r]
              [[-tText] | [FILES, ...]]

Options:
  -n    - Specify nickname to paste with
          (default: ENV['USER'] || 'unknown')
  -d    - Description of paste (default: none)
  -l    - Language for syntax highlighting
          (default: Ruby unless -R option is passed: then Plain Text)
  -c    - Convert tabs to specified number of spaces (default: No)
  -r    - Display only rubyurl for this paste
          (default: both rafb & rubyurl)
  -R    - Rafb only - don't get a rubyurl for this paste
  -t    - Specify text on commandline, rather than reading files.
          If no -t or filenames are supplied, STDIN is read.
          -t precludes reading of any file.

  To get a list of valid language and tab-conversion lengths, you can
  just pass the appropriate option with no value, e.g.

    ./cat2rafb.rb -l
    ./cat2rafb.rb -c

Examples:
  ./cat2rafb.rb somefile.txt
  ./cat2rafb.rb -nMyNick -lC++ -R myfile.c
  ./cat2rafb.rb -n'Long Nick' -d'Ruby code' -t'print if ~/^\d+:/' -r
  ./cat2rafb.rb -c2 -lruby -nmetoo -d'From stdin'

Thanks for another interesting quiz, a rafb paster seems like a good
thing to have :)
0b561a629b87f0bbf71b45ee5a48febb?d=identicon&s=25 Dave Burt (Guest)
on 2006-05-03 18:56
(Received via mailing list)
http://dave.burt.id.au/ruby/nopaste.rb

# nopaste.rb - a command-line interface to http://rafb.net/paste
# Usage: nopaste.rb [options]
# Options:
#    -l, --lang LANGUAGE      Language of snippet (default Plain Text)
#                             C89, C, C++, C#, Java, Pascal, Perl, PHP,
#                             PL/I, Python, Ruby, SQL, VB, Plain Text
#    -n, --nick NICKNAME      Your nickname (9 char max)
#    -d, --desc DESCRIPTION   Description of the snippet (50 char max)
#    -t, --cvt-tabs [SPACES]  Convert tabs to spaces (default No)
#                             No, 2, 3, 4, 5, 6, 7, 8
#    -u, --rubyurl            Shorten the URL using rubyurl.com
#    -a, --agree-to-terms     Agree to the Terms of Use (mandatory)
#    -s, --show-terms         Show the Terms of Use
#    -h, --help               Show this message

D:\Docs\ruby>nopaste.rb -aulR -n"Dave Burt"
#!ruby
puts "hello world"
^Z
Your snippet has been uploaded:
 http://rubyurl.com/i6U

This program should also be usable as a library; in particular,
NoPaste.paste(text, options) and RubyUrl.shorten(url).
The command-line code is just this:
  opts = NoPaste.options  # process ARGV
  url = NoPaste.paste(ARGF.read, opts)
  url = RubyUrl.shorten(url) if opts[:rubyurl]
  puts "Your snippet has been uploaded:\n #{url}"

Cheers,
Dave
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2006-05-03 18:57
(Received via mailing list)
On 4/28/06, Ruby Quiz <james@grayproductions.net> wrote:
>
> back.  Bonus points for pushing the URL through http://rubyurl.com/ to make it
> more manageable.
>
> cat2rafb could work like cat, taking files as input or text until ^D after
> entering the command.
>
>


I decided I didn't like rafb's Ruby highlighting, so I set up an
alternate server that uses the "syntax" gem to handle it.  It uses the
simply_restful plugin to expose a REST API for creating pastes.

Here's a quiz submission that posts to rpaste, instead of rafb.net:
http://rpaste.com/paste/7

Feature requests and better CSS submissions welcome. :)

--Wilson.
4b174722d1b1a4bbd9672e1ab50c30a9?d=identicon&s=25 Ryan Leavengood (Guest)
on 2006-05-03 18:57
(Received via mailing list)
On 4/30/06, Wilson Bilkovich <wilsonb@gmail.com> wrote:
>
> I decided I didn't like rafb's Ruby highlighting, so I set up an
> alternate server that uses the "syntax" gem to handle it.  It uses the
> simply_restful plugin to expose a REST API for creating pastes.
>
> Here's a quiz submission that posts to rpaste, instead of rafb.net:
> http://rpaste.com/paste/7
>
> Feature requests and better CSS submissions welcome. :)

Wow, now talk about an interesting way of solving this quiz. You
really thought outside the box, eh?

Anyhow, personally I like the look of the site (my standard VIM setup
is a black background with white text.) Also the syntax highlighting
is nice looking.

Ryan
C2479d02d5795b2186ed86547dcba098?d=identicon&s=25 Sean Carley (Guest)
on 2006-05-03 19:06
(Received via mailing list)
It isn't pretty and it isn't feature rich, but it does get the job done.

See also: http://rubyurl.com/HgY

#!/usr/bin/ruby
require 'uri'
require 'net/http'

result =
Net::HTTP.post_form(URI.parse('http://rafb.net/paste/paste.php'),
                             {:text => ARGF.readlines,
                              :nick => 'paste user',
                              :lang => 'Ruby'})
result = Net::HTTP.get_response 'rubyurl.com',

'/rubyurl/remote?website_url=http://rafb.net' + result['location']
puts result['location'].sub('rubyurl/show/', '')


Sean Carley
This topic is locked and can not be replied to.