简体   繁体   English

在视图中显示来自HTTparty的GET请求

[英]Displaying GET request from HTTparty on view

I currently have a simple ruby file named example.rb . 我目前有一个简单的ruby文件,名为example.rb How can I make a view that allows a user to submit information into a form and then have the information from the GET request returned to them? 如何制作一个视图,允许用户将信息提交到表单中,然后将GET请求中的信息返回给他们? I understand how to use these requests from the console, but not from the front-end. 我了解如何从控制台(而不是前端)使用这些请求。

Resources on this topic would also be greatly appreciated. 有关此主题的资源也将不胜感激。

require 'rubygems'
require 'httparty'

class StackExchange
  include HTTParty
  base_uri 'api.stackexchange.com'

  def initialize(service, page)
    @options = {query: {site: service}}
  end

  def questions
    self.class.get('/2.2/questions', @options)
  end

  def users
    self.class.get('/2.2/users', @options)
  end
end

stack_exchange = StackExchange.new('stackoverflow',1)
puts stack_exchange.users

Make sure the HTTParty gem is in your application's Gemfile . 确保HTTParty gem在应用程序的Gemfile

Take example.rb and put it in /app/models/stack_exchange.rb — yes the file name does matter[0] (this isn't the purists place to put this, but for beginners it's fine and perfectly acceptable). example.rb并将其放在/app/models/stack_exchange.rb -是的,文件名确实很重要[0](这不是纯粹主义者放置此名称的地方,但对于初学者而言,这是很好的并且完全可以接受的)。 Remove the code at the bottom you're using to test it as well. 还要删除用于测试它的底部的代码。

in routes.rb add this route: get '/test' => 'application#test' routes.rb添加以下路由: get '/test' => 'application#test'

in your application_controller.rb add this method: 在您的application_controller.rb添加以下方法:

def test
  stack_client = StackExchange.new('stackoverflow', 1)
  @users = stack_client.users
end

in app/views/application/test.html.erb put the following: app/views/application/test.html.erb输入以下内容:

<% @users.each do |user| %><%=user.inspect%><br/><br/><% end %>

Note: I would otherwise recommend adding views to ApplicationController but because I don't know anything about your application, I'll default to it. 注意:否则我建议将视图添加到ApplicationController但是由于我对您的应用程序一无所知,因此将默认使用它。

hit http://localhost:3000/test and you should see the expected result. 点击http:// localhost:3000 / test ,您应该会看到预期的结果。

[0] Rails does a lot "magic" under the scenes — it's really not magic but metaprogramming — where it tries to assume a lot of things about your application structure and naming conventions. [0] Rails在幕后做了很多“魔术”,这实际上不是魔术,而是元编程,在这种情况下,Rails尝试承担有关您的应用程序结构和命名约定的许多事情。 If your class was named Stackexchange (note the lowercase e ), stackexchange.rb would be automatically "mapped" to the class Stackexchange . 如果你的类被命名为Stackexchange (注意是小写e ), stackexchange.rb会自动“映射”到类Stackexchange More info: http://guides.rubyonrails.org/autoloading_and_reloading_constants.html 更多信息: http : //guides.rubyonrails.org/autoloading_and_reloading_constants.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM