Использование RESTFul Webservice Ruby on Rails 4 с HTTParty

В настоящее время я разрабатываю приложение Ruby on Rails. Главная особенность — форма поиска с одним текстовым полем ввода. Затем ввод следует использовать в качестве параметра запроса для веб-службы RESTful.

Базовый uri веб-сервиса — https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/. Запрос получает два параметра: String в качестве входных данных для поиска и api_key. Пример запроса выглядит так: curl --request GET 'https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/<name>?api_key=<api_key>' --include

Веб-сервис отправляет ответ в формате JSON.

Моя первоначальная реализация выглядит так:

Я создал класс для переноса вызова веб-сервиса:

/app/models/summoner.rb
# This class encapsulates the riot summoner webservice api    
class Summoner 
    include HTTParty 

    # The webservice' base_uri
    base_uri "https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name"     

    # The webservice' response format
    format :json     

    # The api_key used for the webservice call
    @api_key = "<my_api_key>"    

    # Create attributes and accessors for each of the response attributes
    attr_accessor :id, :name, :profile_icon_id, :revision_date, :summoner_level    

    # Create a new Summor with Summor.new
    def initialize(id, name, profile_icon_id, revision_date, summoner_level)
        self.id = id
        self.name = name
        self.profile_icon_id = profile_icon_id
        self.revision_date = revision_date
        self. summoner_level = summoner_level
    end 

    # The find method called with the input of the controller
    def self.find(summoner_name)
        # Create the response, therefore build the parameters
        response = get("/#{summoner_name}?api_key=" + @api_key)
        if response.success?
              # Yay, we got a result! Lets create a new Summoner then!
              self.new(response["id"], response["name"], response["profileIconId"], response["revisionDate"], response["summonerLevel"])
        else
             # Something went wrong, raise it to show!
             raise response.response
    end
end

конец


Соответствующий контроллер находится здесь:

/app/controllers/pages_controller.rb
# This class defines the controller for pages and their corresponding actions
class PagesController < ApplicationController
    before_action :set_summoner, only: [:home]

# The home action, if search params have been set, execute Summoner.find
def home
    if search_params
        logger.debug "Got params: #{search_params}"
        @summoner = Summoner.find(search_params)
    else
        logger.debug "Got no params!"
    end
end

private
    # Use callbacks to share common setup or constraints between actions.
    def set_summoner
        @summoner = Summoner.find(params[:summoner_name])
    end

    # Never trust parameters from the scary internet, only allow the white list   through.
    def search_params
        params.permit(:summoner_name)
    end
end

И, наконец, представление для отображения формы поиска и результатов поиска:

/app/view/pages/home.html.erb
<!-- Create a form to wrap around the search field -->
<%= form_tag(root_path, :method => "get", id: "search-form") do %>
    <%= text_field_tag :summoner_name, params[:summoner_name], placeholder: "Summoner Name" %>
<%= submit_tag "Search", :summoner_name => nil %>
<% end %>
<!-- If the controller has a summoner, render the summonerss id -->
<% if @summoner %>
    <%= form_for @summoner do |f| %>
    <%= f.text_field :id %>
<% end %>
<% end %>

Я иду в правильном направлении с моей первоначальной реализацией?

Если я делаю вызов веб-сервиса с помощью команды curl, он работает нормально, а также вставляет URL-адрес в браузер. Однако, если я использую его из приложения rails, я получаю сообщение об ошибке: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Я ценю любые комментарии / критику!

Привет


person TheDonDope    schedule 06.06.2014    source источник