Class: ArtTypograph::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/art_typograph/request.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Request

Returns a new instance of Request.



21
22
23
# File 'lib/art_typograph/request.rb', line 21

def initialize(options = {})
  @options = self.class.prepare_options(options)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/art_typograph/request.rb', line 7

def options
  @options
end

Class Method Details

.prepare_options(options) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/art_typograph/request.rb', line 65

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

Instance Method Details

#process(text) ⇒ Object

Process text with remote web-service

Parameters:

  • text (String)

    text to process



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/art_typograph/request.rb', line 27

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
<?xml version="1.0" encoding="#{options[:encoding]}" ?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
 <ProcessText xmlns="http://typograf.artlebedev.ru/webservices/">
  <text>#{text.gsub(/&/, '&amp;').gsub(/</, '&lt;').gsub(/>/, '&gt;')}</text>
 <entityType>#{options[:entity_type]}</entityType>
 <useBr>#{options[:use_br]}</useBr>
 <useP>#{options[:use_p]}</useP>
 <maxNobr>#{options[:max_nobr]}</maxNobr>
  </ProcessText>
 </soap:Body>
</soap:Envelope>
END_SOAP

  response = Net::HTTP.new(url.host, url.port).start do |http|
    http.request(request)
  end

  case response
  when Net::HTTPSuccess
    result = if /<ProcessTextResult>\s*((.|\n)*?)\s*<\/ProcessTextResult>/m =~ response.body
      $1.gsub(/&gt;/, '>').gsub(/&lt;/, '<').gsub(/&amp;/, '&').gsub(/(\t|\n)$/, '')
    else
      text
    end
  else
    text
  end
rescue ::Exception => exception
  text
end