rails 网络应用程序上 ruby 的第三方 API 数据

third party API data for ruby on rails web application

我在 rails 网络应用程序上有一个 ruby,它使用第三方 API,它提供了一些我想可视化的数据d3。访问数据的最佳方式是什么?我只用静态数据集练习 d3.js。

我阅读了 How to create d3 graph using data from Rails database 并且我阅读了 AJAX 是什么,但仍然有点迷茫。如果 AJAX 确实是 the 方式,谁能详细说明这个过程?

另外,当我这样做时,最好使用我的 Web 应用程序从第三方 API 检索到的数据,还是 d3 应该直接从第三方获取数据 API ?它有很大的不同吗?

编辑:

为了更直接地回答你的问题,最好先在Rails中得到结果,然后在你的JavaScript中使用它们,只是为了让它更有条理。

此外,在页面加载时进行 AJAX 调用以获取数据与使用 Rails 相比(根据我的经验),异步调用将无法加载数据在 JavaScript 代码尝试访问它之前(如果花费的时间太长)。您必须将 AJAX 调用设置为同步,以便 AJAX 将首先 return 数据,然后执行任何后续代码。如果要 returned 大量数据,可能会导致页面加载时间过长,这对用户体验不利。


您可能需要使用 RestClient gem。

在你的 Gemfile:

gem 'rest-client'

然后运行bundle install.

之后,创建一个模型以将您的 API 用于:

rails g model ModelForMyApi

然后运行rake db:migrate.

在您的 ModelForMyApi 模型中:

class ModelForMyApi < ActiveRecord::Base
    require 'rest_client'

    @url

    def self.getData
        response = RestClient(@url, { :content_type => :json, "Api-Key" => "put your API key here" }
    end

    def self.retrieve_results(myParameter)
         @url = "myApiUrl.com/stuff/?putYourParamNameHere=#{myParameter}"
        JSON.parse(ModelForMyApi.getData)
    end
end

因此,在您的控制器中,您可以执行以下操作:

class ExamplesController < ApplicationController
    def index
        @results = ModelForMyApi.retrieve_results("superCoolParameter")
    end
end

并在您的 index.html.erb 文件中显示结果:

<%= @results %>

这将显示整个 JSON 响应。如果要访问键值对中的值,请看这个例子。

假装你的回复是这样的:

// This is a Rails JSON object, it has arrows.
// See below for how to incorporate this in your JavaScript
{
    "fruit" => "banana",
    "juice" => "orange juice"
}

正在使用

<%= @results['fruit']  %>

在您看来会显示 "banana"。这就是我用 Rails 进行 API 调用的方式。我不知道如何使用 d3.js 来实现,但我认为最好的方法是首先从 API 中获取结果,然后将这些结果包含在 JavaScript 中。

编辑

由于您需要将其与 JavaScript 一起使用,因此在 Rails 中解析 JSON 响应 可能不是最佳方法。在这种情况下,最好完全按照我上面所说的去做,但是从 self.retrieve_results 方法中删除 JSON.parse() 函数。这将 return 一个普通的 JSON 对象而不是 Rails JSON 对象。

因此在 ModelForMyApi 中,从 return 行中删除 JSON.parse

class ModelForMyApi < ActiveRecord::Base
    require 'rest_client'

    @url

    def self.getData
        response = RestClient(@url, { :content_type => :json, "Api-Key" => "put your API key here" }
    end

    def self.retrieve_results(myParameter)
         @url = "myApiUrl.com/stuff/?putYourParamNameHere=#{myParameter}"
        ModelForMyApi.getData  #JSON.parse was removed 
    end
end

在你的 JavaScript 中,你所要做的就是:

var jsonObj = #{@results};

// Output to log to see all the results you can play with
console.log(jsonObj);

然后,使用上面相同的 JSON 示例 ({"fruit": "banana", "juice": "orange juice"}),您可以在 JavaScript 中访问 JSON,如下所示:

jsonObj.fruit  // Will output "banana"

现在您可以在 d3.js 代码中使用 API 结果。


您需要从 Rails 方法中删除 JSON.parse 的原因是,当您在 Rails 方法中使用它时,它会使您的响应如下所示:

//Javascript cannot interpret the arrows
{
    "fruit" => "banana",
    "juice" => "orange juice"
}

但你需要它看起来像这样:

//JavaScript likes colons. No pun intended.
{
    "fruit": "banana",
    "juice": "orange juice"
}