Skip to content

Instantly share code, notes, and snippets.

@nomnel
Created March 14, 2012 04:05
Show Gist options
  • Save nomnel/2033979 to your computer and use it in GitHub Desktop.
Save nomnel/2033979 to your computer and use it in GitHub Desktop.
全裸で学ぶMVC(ruby+Sinatra)
# coding: utf-8
require 'rubygems'
require 'sinatra'
require 'open-uri'
require 'rexml/document'
helpers do
include Rack::Utils; alias_method :h, :escape_html
end
class Zenra
def initialize(position='動詞', text='全裸で')
@appid = 'YOUR_APP_ID'
@position = position
@text = text
@base_url = 'http://jlp.yahooapis.jp/MAService/V1/parse'
end
def zenrize(sentence)
raise "appid is necessary!" if @appid.nil? || @appid.empty?
raise "Japanese sentence is necessary!" if sentence.nil? || sentence.empty?
req = "#{@base_url}?results=ma&appid=#{@appid}&sentence=#{URI.encode(sentence)}"
res = open(req)
xml = REXML::Document.new(res.read)
return sentence if xml.elements['ResultSet/ma_result/total_count'].text == '0'
result = ''
xml.elements.each('ResultSet/ma_result/word_list/word') do |e|
result << @text if e.elements['pos'].text == @position
result << e.elements['surface'].text
end
result
end
end
get '/' do
erb :index
end
post '/result' do
@model = Zenra.new
erb :result, :locals => {:res => @model.zenrize(params[:text])}
end
__END__
@@ layout
<!DOCTYPE html>
<html>
<head><title>zenrize</title></head>
<body style="width:500px;margin:0 auto;"><h1>zenrize</h1><%= yield %></body>
</html>
@@ index
<form action="/result" method="post">
<textarea rows="3" cols="60" name="text"></textarea>
<br />
<input type='submit' value='zenrize' />
</form>
@@ result
<p><%= h res %></p>
<a href='/'>戻る</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment