다른 도메인에서 RESTful 웹 서비스를 사용하기위한 적절한 "철도 방법"은 무엇입니까?
RESTful 웹 서비스 API를 사용하는 Ruby on Rails 애플리케이션을 작성하여 결과에 대한 로직을 수행 한 다음 해당 데이터를 내 뷰에 표시하고 싶습니다. 예를 들어 search.twitter.com에서 검색하는 프로그램을 작성하고 싶다고 가정 해 보겠습니다. 순수한 루비를 사용하여 다음 방법을 만들 수 있습니다.
def run(search_term='', last_id=0)
@results = []
url = URI.parse("http://search.twitter.com")
res = Net::HTTP.start(url.host, url.port) do |http|
http.get("/search.json?q=#{search_term}&since_id=#{last_id.to_s}")
end
@results = JSON.parse res.body
end
나는 그 메소드를 Rails 컨트롤러에 private 메소드로 드롭하고 싶었지만, 나의 일부는 이것을하기위한 더 나은 "Rails"방법이 있다고 생각한다. 모범 사례 접근 방식이 있습니까 아니면 이것이 정말 최선의 방법입니까?
여러 프로젝트에서 사용한 HTTParty라는 플러그인 / 젬이 있습니다.
http://johnnunemaker.com/httparty/
HTTParty를 사용하면 웹 서비스를 쉽게 사용하고 결과를 해시로 구문 분석 할 수 있습니다. 그런 다음 해시 자체를 사용하거나 결과로 하나 이상의 모델 인스턴스를 인스턴스화 할 수 있습니다. 나는 그것을 두 가지 방법으로했다.
트위터 예제의 경우 코드는 다음과 같습니다.
class Twitter
include HTTParty
base_uri 'twitter.com'
def initialize(u, p)
@auth = {:username => u, :password => p}
end
# which can be :friends, :user or :public
# options[:query] can be things like since, since_id, count, etc.
def timeline(which=:friends, options={})
options.merge!({:basic_auth => @auth})
self.class.get("/statuses/#{which}_timeline.json", options)
end
def post(text)
options = { :query => {:status => text}, :basic_auth => @auth }
self.class.post('/statuses/update.json', options)
end
end
# usage examples.
twitter = Twitter.new('username', 'password')
twitter.post("It's an HTTParty and everyone is invited!")
twitter.timeline(:friends, :query => {:since_id => 868482746})
twitter.timeline(:friends, :query => 'since_id=868482746')
마지막으로, 위의 코드를 사용할 수도 있지만 컨트롤러가 아닌 모델에 코드를 포함해야합니다.
Restclient 는이 문제에 대한 정말 좋은 해결책입니다.
require 'rest_client'
RestClient.get 'http://example.com/resource'
RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}}
로부터 추가 정보 .
원격 RESTful 웹 서비스도 Ruby on Rails로 생성 된 경우 ActiveResource 를 사용하면됩니다.
귀하의 Twitter 예제에 대한 응답으로 이를 자동화하는 데 도움 이되는 Twitter Gem 이 있습니다.
I think Faraday deserves a mention here. Really nice interface, and powerful concept of middleware.
https://github.com/lostisland/faraday
ReferenceURL : https://stackoverflow.com/questions/748614/what-is-the-proper-rails-way-to-consume-a-restful-web-service-on-another-domai
'Development Tip' 카테고리의 다른 글
array.contains의 jquery 버전 (0) | 2021.01.07 |
---|---|
.NET은 Java Properties 클래스에 해당하는 속성 파일을로드하고 구문 분석 할 수 있습니까? (0) | 2021.01.07 |
POM의 Maven 업데이트 종속성 (0) | 2021.01.07 |
"bool"과 "bool"의 차이점은 무엇입니까? (0) | 2021.01.06 |
C #에서 "As"키워드의 요점은 무엇입니까? (0) | 2021.01.06 |