Skip to content

Instantly share code, notes, and snippets.

@rondy
Created April 21, 2012 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondy/2439530 to your computer and use it in GitHub Desktop.
Save rondy/2439530 to your computer and use it in GitHub Desktop.
Michealis Dictionary
$ michaelis ruby
Michealis Dictionary
Translate: ruby (ingles-portugues)

ruby
ru.by
 n 1 Min rubi, rubim. 2 cor do rubi. 3 algo semelhante ao rubi em cor como: vinho tinto, carbúnculo, sangue. 4 Typogr tipo de corpo 5 1/2. • vt ruborizar. • adj da cor do rubi, vermelho-vivo.
---
#!/usr/bin/env ruby
require "rubygems"
require "nokogiri"
require "net/http"
require "uri"
class Michaelis
LANGUAGES_MAPPING = {
"eng" => "ingles",
"pt" => "portugues"
}
attr_reader :term
def initialize(term, from=nil, to=nil)
@term, @from, @to = term, from, to
@results = []
end
def translate
@results = doc.css("div#tdcontents > p:not(#contents)").collect do |p|
if p.at("span.palavra")
{
word: p.at("span.palavra").content,
word_with_dots: p.at("span.palavraComPontos").content,
description: p.at("span.descricao").content
}
end
end.compact
self
end
def from
LANGUAGES_MAPPING.fetch(@from, "ingles")
end
def to
LANGUAGES_MAPPING.fetch(@to, "portugues")
end
def to_s
if @results.empty?
%Q(Not definition found for "#{term}".)
else
@results.collect do |translation|
Array.new.tap do |line|
line << translation[:word]
line << translation[:word_with_dots] unless translation[:word_with_dots] == translation[:word]
line << translation[:description]
line << "---"
end.join("\n")
end
end
end
private
def doc
Nokogiri::HTML(michaelis_response, nil, "UTF-8")
end
def michaelis_response
Net::HTTP.get_response(uri).body
end
def language
"#{from}-#{to}"
end
def uri
URI.parse("http://michaelis.uol.com.br/moderno/ingles/index.php?lingua=#{language}&palavra=#{URI.escape(term.to_s)}")
end
end
class OptionsParser
def initialize(args=[])
@args = args.join(" ")
end
def self.[](args)
new(args).parse
end
def parse
[term, from, to]
end
def term
tokens.first
end
def from
options.fetch("--from", "eng")
end
def to
options.fetch("--to", "pt")
end
private
def options
Hash[tokens[1..-1].collect { |token| token.split(" ") }]
end
def tokens
@args.split('--').collect(&:strip)
end
end
term, from, to = OptionsParser[ARGV]
michaelis = Michaelis.new(term, from, to)
puts "Michealis Dictionary"
puts "Translate: %s (%s-%s)" % [michaelis.term, michaelis.from, michaelis.to]
puts
puts michaelis.translate.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment