require 'net/http'
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash/reverse_merge'
module ArtTypograph
class Request
attr_reader :options
class_attribute :url, :instance_writer => false
self.url = URI.parse('http://typograf.artlebedev.ru/webservices/typograf.asmx')
class_attribute :default_options, :instance_writer => false
self.default_options = {
:entity_type => :no,
:use_br => false,
:use_p => true,
:max_nobr => 3,
:encoding => 'UTF-8'
}
def initialize(options = {})
@options = self.class.prepare_options(options)
end
# Process text with remote web-service
# @param [String] text text to process
def process(text)
request = Net::HTTP::Post.new(url.path, {
'Content-Type' => 'text/xml',
'SOAPAction' => '"http://typograf.artlebedev.ru/webservices/ProcessText"'
})
request.body = <<-END_SOAP
#{text.gsub(/&/, '&').gsub(/, '<').gsub(/>/, '>')}
#{options[:entity_type]}
#{options[:use_br]}
#{options[:use_p]}
#{options[:max_nobr]}
END_SOAP
response = Net::HTTP.new(url.host, url.port).start do |http|
http.request(request)
end
case response
when Net::HTTPSuccess
result = if /\s*((.|\n)*?)\s*<\/ProcessTextResult>/m =~ response.body
$1.gsub(/>/, '>').gsub(/</, '<').gsub(/&/, '&').gsub(/(\t|\n)$/, '')
else
text
end
else
text
end
rescue ::Exception => exception
text
end
def self.prepare_options(options)
o = options.reverse_merge(default_options)
[:use_br, :use_p].each do |key|
val = o[key]
o[key] = case val
when true then 1
when false then 0
when 0, 1 then val
else raise ArgumentError, "Unknown #{key}: #{val}"
end
end
o[:entity_type] = case o[:entity_type]
when :html then 1
when :xml then 2
when :no then 3
when :mixed then 4
when 1..4 then o[:entity_type]
else raise ArgumentError, "Unknown entity_type: #{o[:entity_type]}"
end
o
end
end
end