Last active
August 29, 2015 14:23
-
-
Save hiroara/6b0c0b20f696bb6bacff to your computer and use it in GitHub Desktop.
Encode/Decode string using encodemaniax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'uri' | |
require 'net/http' | |
require 'cgi' | |
require 'nokogiri' | |
EM_URL = URI.parse('http://encodemaniax.com') | |
def build_query data, charset='utf-8' | |
{ charset: charset, data: data }.map do |key, val| | |
"#{key}=#{CGI.escape(val)}" | |
end.join('&') | |
end | |
def build_request_path path, data, charset='utf-8' | |
query = build_query data, charset | |
query.empty? ? path : "#{path}?#{query}" | |
end | |
def request path, data, charset='utf-8' | |
Net::HTTP.start(EM_URL.host, EM_URL.port) { |http| http.get(build_request_path(path, data, charset)) } | |
end | |
def process type, data, id=nil | |
body = request('/', data).body | |
html = Nokogiri::HTML.parse body | |
if id | |
puts html.xpath("//*[@class=\"#{type}-results\"]//*[@id=\"#{id}\"]//pre").text | |
else | |
html.xpath("//*[@class=\"#{type}-results\"]/div[@id]").map.with_index do |div| | |
puts "--- #{div.attribute('id')} ---" | |
puts div.children.xpath('.').text.split("\n").map(&:strip).reject(&:empty?).compact | |
end | |
end | |
end | |
def encode data, id=nil | |
process 'encode', data, id | |
end | |
def decode data, id=nil | |
process 'decode', data, id | |
end | |
require 'optparse' | |
opt = OptionParser.new | |
options = { decode: false } | |
opt.on('-d') { options[:decode] = true } | |
opt.parse!(ARGV) | |
case ARGV.length | |
when 2 | |
id, data = ARGV | |
options[:decode] ? decode(data, id) : encode(data, id) | |
when 1 | |
data = ARGV.first | |
options[:decode] ? decode(data) : encode(data) | |
else throw ArgumentError | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment