【发布时间】:2018-02-21 18:05:40
【问题描述】:
所以我创建了这个请求,它给了我一个 json 的响应。
require 'dotenv/load'
require 'faraday'
class OverviewController < ApplicationController
def api_key
ENV["API_KEY"]
end
def url
"https://example.com"+api_key
end
def index
conn = Faraday.new(url, request: {open_timeout: 1, timeout: 1}) do |c|
c.response :json, :content_type => /\bjson$/
c.adapter Faraday.default_adapter
end
response = conn.get url
@hash = response.body['data']
end
end
回复:
{
"type": "products",
"version": "x.x.x",
"data": {
"Product 1": {
"title": "xxx",
"attributes": {
"x"=1
},
"id": 22,
"name": "Product 1"
},
"Product 2": {
"title": "xXx",
"attributes": {
"x"=2
},
"id": 25,
"name": "Product 2"
},
...
到目前为止效果很好。但是由于这个 json 中的数据变化很少,并且有一个政策是不尽可能多地请求 api,所以我想缓存我的结果。
我用“faraday-http-cache”尝试了不同的解决方案,但我无法让它工作。但我喜欢不使用其他库。
我阅读了“rails - Guides - 缓存”部分,我认为我需要低级缓存 Rails.cache.fetch
如果有人可以帮助我,我会很高兴:-)
编辑(在恐慌的评论之后): 我试过了,但我需要更多帮助
require 'dotenv/load'
require 'faraday'
class StatsClient
def api_key
ENV["API_KEY"]
end
def url
"https://example.com"+api_key
end
def index
conn = Faraday.new(url, request: {open_timeout: 1, timeout: 1}) do |c|
c.response :json, :content_type => /\bjson$/
c.adapter Faraday.default_adapter
end
response = conn.get url
@hash = response.body['data']
end
end
class OverviewController < ApplicationController
def index
@hash = Rails.cache.fetch('something', expires_in: 15.minutes) do
StatsClient.products
end
end
end
像这样?实际上必须是 'something'。我还收到“无法识别 StatsClient.products 的错误。
【问题讨论】:
标签: ruby-on-rails ruby faraday