2014-06-19 2 views
2

API로 작업하는 초보자입니다. 나는 Forecast API으로 일하려고합니다. 처음에는 공부하고 배우기를 좋아하기 때문에 나는 official wrapper을 사용하고 싶지 않습니다.API로 작업하는 레일

class Forecast 
    include HTTParty 

    base_uri "api.forecast.io/forecast/#{@api_key}/#{@latitude},#{@longitude}" 

    def initialize(api_key,latitude,longitude) 
    self.api_key = api_key 
    self.latitude = latitude 
    self.longitude = longitude 
    end 


end 

이제 초기화 후 다음 단계가되어야합니다. 나는 httparty 보석 예제를 사용하여 이해하려고했지만 정확하게 할 수있는 것을 파악할 수 없습니다.

API를 사용하여 & 관련 리소스를 고칠 수 있습니까?

답변

4

API로 작업 할 때 httpsy gem을 사용하지 않고 대신 typhoeus gem을 사용하여 병렬 http 요청을 허용하므로 동시성을 사용할 수 있지만 httpaty를 사용하는 경우 아래 예제도 작동합니다. 간단한 예제를 사용하여 API 사용 방법을 보여 드리겠습니다. 제품 목록을 가져 오기 위해 JSON API 서비스와 통신하려고한다고 가정 해 보겠습니다.

서비스 엔드 포인트의 URL이처럼 보이는 index 행동으로 products_controller.rb을 가질 수 있습니다, 응용 프로그램에서 http://path/to/products.json

입니다 :

class ProductsController < ApplicationController 
    def index 
    # make a http request to the api to fetch the products in json format 
    hydra = Typhoeus::Hydra.hydra 
    get_products = Typhoeus::Request.new('http://path/to/products.json') 
    get_products.on_complete do |response| 
     products = MultipleProducts.from_json(response.body) 
     @products = products.products 
    end 
    hydra.queue get_products 
    hydra.run 
    end 
end 

이의 말을하자 그 http://path/to/products.json 반환에 HTTP 요청 다음 json

{"products" [{"id": 1, 
    "name": "First product", 
    "description": "Description", 
    "price": "25.99"}, {"id": 2, 
    "name": "Second product", 
    "description": "Description", 
    "price": "5.99"}] 

이 json은 이름이 class 인 랩으로 처리 할 수 ​​있습니다.

class MultipleProducts 
    attr_reader :products 
    def initialize(attributes) 
    @products = attributes[:products] 
    end 
    def self.from_json(json_string) 
    parsed = JSON.parse(json_string) 
    products = parsed['products'].map do |product| 
     Product.new(product) 
    end 
    new(products: products) 
    end 
end 

그런 다음 제품이 같은 모델을 만들 수 ActiveModel를 사용할 수 있습니다 :이처럼 보이는 전자 같은 multiple_products.rb 당신의 app/views/products/index.html에서

class Product 
    include ActiveModel::Serializers::JSON 
    include ActiveModel::Validations 
    ATTRIBUTES = [:id, :name, :description, :price] 
    attr_accessor *ATTRIBUTES 
    validates_presence_of :id, :name, :price 

    def initialize(attributes = {}) 
    self.attributes = attributes 
    end 

    def attributes 
    ATTRIBUTES.inject(ActiveSupport::HashWithIndifferentAccess.new) do |result, key| 
     result[key] = read_attribute_for_validation(key) 
     result 
    end 
    end 

def attributes= (attrs) 
    attrs.each_pair {|k, v| send("#{k}=", v)} 
end 

def read_attribute_for_validation(key) 
    send(key) 
end 
end 

, 당신은 할 수 있습니다 :

<h1>Products Listing</h1> 
<ul> 
    <% @products.each do |product| %> 
    <li>Name: <%= product.name %> Price: <%= product.price %> </li> 
    <% end %> 
</ul> 

그러면 API에서 가져온 모든 제품이 나열됩니다. 이것은 단지 간단한 예일 뿐이며 API로 작업 할 때 훨씬 더 복잡합니다. 자세한 내용은 Service-Oriented Design with Ruby and Rails을 읽어보십시오.

+0

WhoOa ..! 그게 복잡했습니다. 나는 API로 개발하기 위해 많은 것을 배워야한다고 생각한다. 모든 라이브러리를 이해하는 간단한 방법을 찾아야합니다. 그러나 thnx 책을 추천 많이. – arjun

관련 문제