2015-09-07 3 views
-2

Я пытаюсь позвонить, но я все время получаю сообщение об ошибке. Это мой код:Как мне вызвать функцию в Ruby?

require 'rubygems' 
require 'net/http' 
require 'uri' 
require 'json' 

class AlchemyAPI 

    #Setup the endpoints 
    @@ENDPOINTS = {} 
    @@ENDPOINTS['taxonomy'] = {} 
    @@ENDPOINTS['taxonomy']['url'] = '/url/URLGetRankedTaxonomy' 
    @@ENDPOINTS['taxonomy']['text'] = '/text/TextGetRankedTaxonomy' 
    @@ENDPOINTS['taxonomy']['html'] = '/html/HTMLGetRankedTaxonomy' 

    @@BASE_URL = 'http://access.alchemyapi.com/calls' 

    def initialize() 

    begin 
     key = File.read('C:\Users\KVadher\Desktop\api_key.txt') 
     key.strip! 

     if key.empty? 
      #The key file should't be blank 
      puts 'The api_key.txt file appears to be blank, please copy/paste your API key in the file: api_key.txt' 
      puts 'If you do not have an API Key from AlchemyAPI please register for one at: http://www.alchemyapi.com/api/register.html'    
      Process.exit(1) 
     end 

     if key.length != 40 
      #Keys should be exactly 40 characters long 
      puts 'It appears that the key in api_key.txt is invalid. Please make sure the file only includes the API key, and it is the correct one.' 
      Process.exit(1) 
     end 

     @apiKey = key 
    rescue => err 
     #The file doesn't exist, so show the message and create the file. 
     puts 'API Key not found! Please copy/paste your API key into the file: api_key.txt' 
     puts 'If you do not have an API Key from AlchemyAPI please register for one at: http://www.alchemyapi.com/api/register.html' 

     #create a blank file to hold the key 
     File.open("api_key.txt", "w") {} 
     Process.exit(1) 
    end 
    end 

    # Categorizes the text for a URL, text or HTML. 
    # For an overview, please refer to: http://www.alchemyapi.com/products/features/text-categorization/ 
    # For the docs, please refer to: http://www.alchemyapi.com/api/taxonomy/ 
    # 
    # INPUT: 
    # flavor -> which version of the call, i.e. url, text or html. 
    # data -> the data to analyze, either the the url, text or html code. 
    # options -> various parameters that can be used to adjust how the API works, see below for more info on the available options. 
    # 
    # Available Options: 
    # showSourceText -> 0: disabled (default), 1: enabled. 
    # 
    # OUTPUT: 
    # The response, already converted from JSON to a Ruby object. 
    # 
    def taxonomy(flavor, data, options = {}) 


    unless @@ENDPOINTS['taxonomy'].key?(flavor) 
     return { 'status'=>'ERROR', 'statusInfo'=>'Taxonomy info for ' + flavor + ' not available' } 

    end 

    #Add the URL encoded data to the options and analyze 
    options[flavor] = data 
    return analyze(@@ENDPOINTS['taxonomy'][flavor], options) 
    print 

    end 

    **taxonomy(text,"trees",1)** 

end 

** ** Я пришел ко мне. Я делаю что-то неправильное. Ошибка я получаю это:

C:/Users/KVadher/Desktop/testrub:139:in `<class:AlchemyAPI>': undefined local variable or method `text' for AlchemyAPI:Class (NameError) 
    from C:/Users/KVadher/Desktop/testrub:6:in `<main>' 

Я чувствую, как будто я звоню, как обычно, и что есть что-то не так с самого апи кода? Хотя я могу ошибаться.

+1

Что такое «текст» в строке «таксономия (текст,« деревья », 1)». Это из-за 'text' не определено. –

+0

Но когда я определяю текст, я получаю следующую ошибку: C:/Users/KVadher/Desktop/testrub: 140: in ' ': неопределенный метод' таксономия' для AlchemyAPI: класс (NoMethodError) \t от C:/Users/KVadher/Desktop/testrub: 6: in '

' – semiflex

+1

Я думаю, что« таксономия (текст, «деревья», 1) «строка должна быть вне класса вроде этого. 'al = AlchemyAPI.new al.taxonomy (текст,« деревья », 1)' С вашим определенным «текстом». –

ответ

1

Да, как говорит снег снега, вызов функции (метода) должен быть вне класса. Методы определяются вместе с классом.

Также Options должен быть Hash, а не номером, как вы звоните options[flavor] = data, что вызовет у вас еще одну проблему.

Я полагаю, возможно, вы хотели поставить text в кавычки, так как это один из ваших вкусов.

Кроме того, поскольку вы объявили класс, это называется методом экземпляра, и вы должны сделать экземпляр класса использовать это:

my_instance = AlchemyAPI.new 
my_taxonomy = my_instance.taxonomy("text", "trees") 

Этого достаточно, чтобы заставить его работать, похоже, у вас есть способы пойти, чтобы все это работало. Удачи!