如何使用rest-client在rails中显示特定数据

how to use rest-client to display specific data in rails

我连接 api 以显示特定数据,但不显示如何使用此 rails。 不知道把代码放在 modelcontroller

需要如何使用此代码连接 rails 应用

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文件夹中创建服务文件夹,也可以使用lib文件夹,也可以创建一个任务。

确保重新启动服务器和 url-地址!

#|- 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')

并在控制器的任何地方调用它...

#if wanna dynamically call url, api key or smth else, just initialize in the class.
rdb = RestdbApi.new
body = rdb.call
puts body