gpt4 book ai didi

ruby-on-rails - 使用 Ruby Controller 读取 Instagram JSON 并传递给 View,使用 HTTParty gem

转载 作者:行者123 更新时间:2023-12-04 08:56:14 24 4
gpt4 key购买 nike

我正在尝试学习用 Ruby 处理 JSON。我经历了很多教程,但更加困惑,所以我尝试通过这样做来学习。
在这里,我试图从 Instagram 获取用户数据并显示在我的 View 中。我可以访问下面的 JSON,但是 如何到达某些字段和用户名或循环帖子?

# users_controller.rb
require 'httparty'

class UsersController < ApplicationController
include HTTParty

def show
@user = User.find(params[:id])
fetch_instagram("elonofficiall")
end

private
def fetch_instagram(instagram_username)
url = "https://www.instagram.com/#{instagram_username}/?__a=1"
@data = HTTParty.get(url)
return @data
end
end
# show.html.erb
# the code below is just to try if I get anything
<%= @data %>
<% @data.each do |data| %>
<p><%= data %></p>
<% end %>

https://www.instagram.com/elonofficiall/?__a=1
enter image description here

最佳答案

首先不要直接从您的 Controller 进行 HTTP 调用。
而是创建一个与 instagram API“对话”的单独类:

# app/clients/instagram_client.rb
class InstagramClient
include HTTParty
base_uri 'https://www.instagram.com'
format :json

def initialize(**options)
@options = options
end

def user(username, **opts)
options = @options.reverse_merge(
'__a' => 1 # wtf is this param?
).reverse_merge(opts)

response = self.class.get("/#{username}", options)
if response.success?
extract_user(response)
else
Rails.logger.error("Fetching Instagram feed failed: HTTP #{response.code}")
nil
end
end

private
def extract_user(json)
attributes = response.dig('graphql', 'user')&.slice('id', 'biography')
attributes ? InstagramUser.new(attributes) : nil
end
end
还有一个类,用于规范应用程序中使用的 API 响应:
# app/models/instagram_user.rb
class InstagramUser
include ActiveModel::Model
include ActiveModel::Attributes
attribute :id
attribute :biography
attribute :username
# etc
end
这只是一个没有保留在数据库中的直接 Rails 模型。 ActiveModel::ModelActiveModel::Attributes让您像使用 ActiveRecord 支持的模型一样传递用于批量分配的属性散列。
这为您提供了一个对象,您可以通过以下方式简单地进行测试:
InstagramClient.new.feed('elonofficiall')
你可以像这样将它集成到你的 Controller 中:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
fetch_instagram(@user.instagram_username)
end

private
def fetch_instagram(instagram_username)
@instagram_user = InstagramClient.new.user(@user.instagram_username)
end
end
混音 HTTParty进入您的 Controller 是一个直接的坏主意,因为 Controller 很难测试,并且 Controller 已经负责响应客户端请求并且不需要更多。
在您的 View 中处理“原始”JSON 响应也不是一个很好的做法,因为它在外部 API 和您的应用程序之间创建了一个硬耦合,并大大增加了您的 View 的复杂性。首先在单独的对象中规范化数据。
<% if @instagram_user %>
<p><%= @instagram_user.username %></p>
<% end %>
如果您想从用户 Instagram 提要中实际获取媒体项目,您需要向 GET https://graph.facebook.com/{ig-user-id}/media 发出另一个 HTTP 请求。 .见 official API documentation .

关于ruby-on-rails - 使用 Ruby Controller 读取 Instagram JSON 并传递给 View,使用 HTTParty gem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63820669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com