Skip to content

Instantly share code, notes, and snippets.

@twtw
Created October 14, 2012 04:53
Show Gist options
  • Save twtw/3887386 to your computer and use it in GitHub Desktop.
Save twtw/3887386 to your computer and use it in GitHub Desktop.
sinatra single file example
# -*- encoding: utf-8 -*-
# detail at http://ithelp.ithome.com.tw/question/10103736
require 'sinatra'
require 'net/http'
require 'open-uri'
require 'json'
require 'yaml'
get '/' do
"Hi, 鐵人五<br /><a href='/env'>環境變數</a>"
end
get '/env' do
env.map{|k,v| "#{k}: #{v}<br />"}
end
get '/rand/novel.?:format?' do
names = more_novel_name
myformat(names, params[:format])
end
def get_utf8_body(url)
uri = URI.parse(url)
res = Net::HTTP.start(uri.host, uri.port) {|http|
http.get(uri.path)
}
# syntax before ruby-1.8.x
#body = Iconv.iconv("UTF-8//IGNORE","BIG5//IGNORE",res.body)
body = res.body.force_encoding('big5').encode('UTF-8')
return body
end
def more_novel_name
url = "http://www.richyli.com/name/novel.asp"
body = get_utf8_body(url)
names = (body.split("\r\n")[52]).strip.gsub(/。/,'').split('、')
return names
end
def myformat(data,format=false)
format = format
if format == 'json'
data.to_json
elsif format == 'yml'
data.to_yaml
else
data.join(',')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment