【问题标题】:how to use rest-client to display specific data in rails如何使用rest-client在rails中显示特定数据
【发布时间】:2018-06-27 16:57:21
【问题描述】:

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

需要如何使用此代码连接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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4


    【解决方案1】:

    您可以在app文件夹中创建服务文件夹,也可以使用lib文件夹,也可以创建任务。

    确保重启服务器和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')
    

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

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

    【讨论】:

    • 谢谢@7urm3n 但我知道代码但不知道如何在rails中使用?
    • @Sdadad 2 分钟更新我的帖子。
    • class GdirectionsController &lt; ApplicationController def index rdb = RestdbApi.new @x= rdb.call end end 时出现这个错误 uninitialized constant GdirectionsController::RestdbApi
    • 更新的帖子添加了config.eager_load_paths,确保也重启服务器
    • config.eager_load_paths 添加到配置中的application.rb 并重新启动服务器,但保留错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    相关资源
    最近更新 更多