法拉第rails从它开始
Faraday rails started with it
我必须显示来自这个网站的数据:https://baconipsum.com/json-api/,但我不知道在我的应用程序中的什么地方编写它的代码。我必须为控制器和视图编写什么代码?
设置法拉第:
bacon = Faraday.new("https://baconipsum.com/") do |f|
f.response :json # automatically parse responses as json
end
在控制器中发送请求:
@bacon = bacon.get("api/", type: 'all-meat', sentences: 1).body # => ["Leberkas frankfurter chicken tongue."]
在视图中使用它:
<% @bacon.each do |meat| %>
<p>
<%= meat %>
</p>
<% end %>
https://lostisland.github.io/faraday/usage/
更新
有多种设置方法。非常简单的设置可能如下所示:
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
private
# NOTE: this method will be accessible in any controller
# that inherits from ApplicationController
def baconipsum
# NOTE: memoize for a bit of performance, in case you're
# making multiple calls to this method.
@baconipsum ||= Faraday.new("https://baconipsum.com/") do |f|
f.response :json
end
end
end
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
# I'm not quite sure what you're trying to do with it;
# change this to fit your use case.
@bacon = baconipsum.get("api/", type: 'all-meat').body
end
end
# app/views/articles/show.html.erb
<% @bacon.each do |meat| %>
<p> <%= meat %> </p>
<% end %>
我必须显示来自这个网站的数据:https://baconipsum.com/json-api/,但我不知道在我的应用程序中的什么地方编写它的代码。我必须为控制器和视图编写什么代码?
设置法拉第:
bacon = Faraday.new("https://baconipsum.com/") do |f|
f.response :json # automatically parse responses as json
end
在控制器中发送请求:
@bacon = bacon.get("api/", type: 'all-meat', sentences: 1).body # => ["Leberkas frankfurter chicken tongue."]
在视图中使用它:
<% @bacon.each do |meat| %>
<p>
<%= meat %>
</p>
<% end %>
https://lostisland.github.io/faraday/usage/
更新
有多种设置方法。非常简单的设置可能如下所示:
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
private
# NOTE: this method will be accessible in any controller
# that inherits from ApplicationController
def baconipsum
# NOTE: memoize for a bit of performance, in case you're
# making multiple calls to this method.
@baconipsum ||= Faraday.new("https://baconipsum.com/") do |f|
f.response :json
end
end
end
# app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
# I'm not quite sure what you're trying to do with it;
# change this to fit your use case.
@bacon = baconipsum.get("api/", type: 'all-meat').body
end
end
# app/views/articles/show.html.erb
<% @bacon.each do |meat| %>
<p> <%= meat %> </p>
<% end %>