Home > Blockchain >  Faraday rails started with it
Faraday rails started with it

Time:05-17

I have to show data from this website: https://baconipsum.com/json-api/ , but I don't know where to write the code of it in my app. What code do I have to write for controllers and in views?

CodePudding user response:

Setup faraday:

bacon = Faraday.new("https://baconipsum.com/") do |f|
  f.response :json # automatically parse responses as json
end

Send a request in the controller:

@bacon = bacon.get("api/", type: 'all-meat', sentences: 1).body # => ["Leberkas frankfurter chicken tongue."]

Use it in the view:

<% @bacon.each do |meat| %>
  <p> 
    <%= meat %>
  </p>
<% end %>

https://lostisland.github.io/faraday/usage/

Update

There are many ways to set it up. Very simple set up could look like this:

# 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 %>
  • Related