Home Displaying GET request from HTTparty on view
Reply: 1

Displaying GET request from HTTparty on view

Jack Moody
1#
Jack Moody Published in 2018-01-13 00:07:03Z

I currently have a simple ruby file named 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? 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
Josh Brody
2#
Josh Brody Reply to 2018-01-13 00:52:31Z

Make sure the HTTParty gem is in your application's 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). Remove the code at the bottom you're using to test it as well.

in routes.rb add this route: get '/test' => 'application#test'

in your application_controller.rb add this method:

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

in app/views/application/test.html.erb put the following:

<% @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.

hit http://localhost:3000/test and you should see the expected result.

[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. If your class was named Stackexchange (note the lowercase e), stackexchange.rb would be automatically "mapped" to the class Stackexchange. More info: http://guides.rubyonrails.org/autoloading_and_reloading_constants.html

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.36522 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO