如何使用rest-client在rails中显示特定数据 [英] how to use rest-client to display specific data in rails
本文介绍了如何使用rest-client在rails中显示特定数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我与 api 连接以显示特定数据,但不显示如何使用此 rails .不知道把代码放在 model
或 controller
i connect with api to display specific data but not how to use this rails .
not know put code in model
or controller
需要如何使用此代码连接rails应用程序
need how to use this code to connect rails app
require 'rest-client'
require 'json'
url = 'https://xxxx.restdb.io/rest/data'
headers =
{
'content-type': "application/json",
'x-apikey': "-------",
'cache-control': "no-cache"
}
req = RestClient.get(url, headers)
we = JSON.parse(req.body)
p we
config/application.rb
更新后的代码
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Version0
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
config.eager_load_paths << Rails.root.join('app/services')
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
推荐答案
你可以在 app 文件夹中创建 service 文件夹,也可以使用 lib 文件夹,也可以创建一个任务.
You can create service folder in the app folder nor can use lib folder, also make a task too.
确保重启服务器和url-address!
Make sure restart the server and url-address!
#|- app
#|-- services
#|--- restdb_api.rb
require 'rest-client'
require 'json'
class RestdbApi
def initialize
@url = 'https://xxxx.restdb.io/rest/data'
@headers = {
'content-type': "application/json",
'x-apikey': "-------",
'cache-control': "no-cache"
}
end
def call
res = RestClient.get(@url, @headers)
body = JSON.parse(res, { symbolize_names: true })
body
end
end
# config/application.rb
config.eager_load_paths << Rails.root.join('app/services')
并在控制器的任何地方调用它...
And call it anywhere in the controller...
#if wanna dynamically call url, api key or smth else, just initialize in the class.
rdb = RestdbApi.new
body = rdb.call
puts body
这篇关于如何使用rest-client在rails中显示特定数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文