Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Monday, May 18, 2009

Pseudo URI Literal

A URI notation is easy to be distinguished. There is almost no confusion about it. Therefore it may be OK that some programming languages have URI Literal. Unfortunately, I have never seen.

I added a something like a URI literal into Ruby.

def http(x)
  "http://#{x}"
end

class Symbol
  def /(o)
    o
  end
end

class String
  def method_missing(*a, &b)
    raise unless a.size == 1
    "#{self}.#{a.first}"
  end

  def /(o)
    "#{self}/#{o}"
  end
end

def method_missing(*a, &b)
  raise unless a.size == 1
  a.first.to_s
end

p http://www.google.com/this/is/a/pen.html
#=> "http://www.google.com/this/is/a/pen.html"

Although this snippet supports only http, it is easy to be extended to handle https, ftp or gopher.

Added on 2009-05-20

I fixed the code to support % notation and to return a URI object by a URI literal as _tad_ suggested. The new code is below:

require 'uri'

def http(x)
  URI.parse "http://#{x}"
end

class Symbol
  def /(o)
    o
  end
end

class String
  def method_missing(*a, &b)
    raise unless a.size == 1
    "#{self}.#{a.first}"
  end

  def /(o)
    "#{self}/#{o}"
  end

  def %(n)
    "#{self}%#{n}"
  end
end

class Integer
  def method_missing(*a, &b)
    raise unless a.size == 1
    "#{self}.#{a.first}"
  end
end

def method_missing(*a, &b)
  raise unless a.size == 1
  a.first.to_s
end

p http://www.google.com/this/is/a/pen.html
#=> #<URI::HTTP:0x7a8c8 URL:http://www.google.com/this/is/a/pen.html>

p http://www.google.com/this/is/a/aaa%20.html
#=> #<URI::HTTP:0x79c98 URL:http://www.google.com/this/is/a/aaa%20.html>

To tell the truth, I finished writing the code in a short time, but at that time blogger.vim didn't work. It tool very long time to fix blogger.vim, and then finally I succeeded it. blogger.vim will be version up soon.

2 comments:

  1. You should define method "%" for URI encoding, and that _is_ already defined as String#% ..!

    So, IMHO, it is desirable not to use String class for the result of http().

    More over, "Foo Literal" should represent a instance of "class Foo." I hope "(http://www.google.com/this/is/a/pen.html
    ).class" result in "URI".

    ReplyDelete

Followers