Class: InstantiatedGrammar

Inherits:
Object
  • Object
show all
Defined in:
lib/nugramserver-ruby/nugramserver-ruby.rb

Overview

Objects of this class act as proxy for instantiated grammars on NuGram Hosted Server.

Instance Method Summary collapse

Constructor Details

#initialize(session, data) ⇒ InstantiatedGrammar

Returns a new instance of InstantiatedGrammar.



136
137
138
139
# File 'lib/nugramserver-ruby/nugramserver-ruby.rb', line 136

def initialize(session, data)
  @session = session
  @data = data
end

Instance Method Details

#get_content(extension = 'abnf') ⇒ Object

Retrieves the source representation of the grammar in the requested format (‘abnf’, ‘grxml’, or ‘gsl’)



149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/nugramserver-ruby/nugramserver-ruby.rb', line 149

def get_content (extension = 'abnf')
  url = URI.parse(self.get_url(extension))
  Net::HTTP.start(url.host, url.port) {|http|
    req = Net::HTTP::Get.new(url.path)
    response = http.request(req)
    case response
      when Net::HTTPSuccess then
         response.body
      else
        response.error!
      end
  }
end

#get_url(extension = 'abnf') ⇒ Object

Returns the URL of the grammar



142
143
144
145
# File 'lib/nugramserver-ruby/nugramserver-ruby.rb', line 142

def get_url (extension = 'abnf')
  grammarUrl = @data['grammarUrl']
  "#{grammarUrl}.#{extension}"
end

#interpret(sentence) ⇒ Object

Computes the semantic interpretation of the given sentence (which must a string). Returns a Python object of ‘False’ if the sentence cannot be parsed by the grammar.



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/nugramserver-ruby/nugramserver-ruby.rb', line 166

def interpret(sentence)
  url = URI.parse(@data['interpreterUrl'])
  sentence = URI.escape(sentence)
  Net::HTTP.start(url.host, url.port) {|http|
    req = Net::HTTP::Post.new(url.path)
    req.body= "responseFormat=json&sentence=#{sentence}"
    req.basic_auth @session.username, @session.password
    response = http.request(req)
    case response
      when Net::HTTPSuccess then
         JSON.parse(response.body)['interpretation']
      else
        response.error!
      end
  }        
end