I am trying to have two separate Ruby programs to communicate, one with the Sinatra gem, and another with the HTTParty gem. What I am attempting to do is post data to the Sinatra program from a HTTP post request in the other program.
This is the code that sends the data.
HTTParty.post('https://notgivingawaymydomain/post_data', {something: foo})
However, I don't know how to receive the data on the other end. I've tried a few things I researched on the internet but none seem to work.
EDIT
My code on the other end is really nothing special at the moment, but I'll put what I've been trying.
post '/post_data' do
#not sure how to access the hash that my post request sent here
end
The post data is available in the params object inside your Sinatra route:
post '/post_data' do
data = params["something"] # => my_value is now 'foo' in this example
#... rest of code
end
Sinatra only parses the data if it is application/x-www-form-urlencoded (which it is in this case) or multipart/form-data. If you wanted to POST another type (e.g. JSON) you would need to parse the request body yourself using request.body:
post '/json_data'
# request.body is an IO object
data = JSON.parse(request.body.read)
end
Be sure to get the syntax of your HTTParty call correct. You need to specify the body: key of the options:
HTTParty.post('http://localhost:4567/post_data', body: {something: "foo"})
if you want to post data via HTTP you need a web-server on the receiving end.
sinatra describes itself as Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort
so in itself it is not a webserver, but it can be run through a webserver to process the data that you post via HTTP. it is bundled with a webserver, so you can start it right away.
if you look at the sinatra README it says
It is recommended to also run gem install thin, which Sinatra will pick up if available.
thin is a reliable webserver that is recommended to run sinatra web applications.
Related
I seem to be missing something basic, as I don't know how to capture and then handle an incoming HTTP Post. I'm a C/C++ developer learning Ruby for the first time, and I've never dealt with web-stuff in my life.
I'm writing my first Slack Webhook, and slack will send data similar to this to my webserver:
token=ZLAmT1sKurm2KwvmYDR9hbiV
team_id=T0001
team_domain=example
channel_id=C2147483705
channel_name=test
user_id=U2147483697
user_name=Steve
command=/weather
text=94070
response_url=https://hooks.slack.com/commands/1234/5678
I have no idea how to accept this POST request, and send it to my application for processing.
I assume it's similar to handling argv and argc for a terminal application, but I'm stuck writing the first few lines.
I've searched for a solution, but it seems like I'm asking the wrong questions.
I currently have a Puma/Sinatra webserver running on heroku, with the Procfile containing:
web: bundle exec puma -p $PORT (I also have no idea what port is assigned to it.)
Similar to this answer, Sinatra provides a DSL to accept POST requests. Within the block, the data will be accessible in the params hash. Something like
post '/my_endpoint' do
content_type :json
#team_id = params[:team_id]
res = do_stuff_with_channel_id params[:channel_id] # passing the value to a custom method example
{my_response: res}.to_json #simple example of returning JSON in response
end
Sinatra Docs on routing
HTH
I'm using the VCR gem and I've figured out how to record an API request to a cassette in JSON format. Now how do I access the information in the body of the response from that cassette?
You can use the following code to access the raw_cassette_bytes method which returns all the data from the VCR cassette:
VCR.use_cassette('path/to/cassette') do |cassette|
puts cassette.send(:raw_cassette_bytes)
end
I have used this when trying to make sure that the ERB template for a VCR cassette looks correct and is generated correctly.
I'm using capybara-webkit to test integration with a third party website (I need javascript).
I want to use vcr to record requests made during the integration test but capybara-webkit doesn't go over net http so vcr is unable to record them. How would I go about writing an adaptor for vcr that would allow me to record the reqeusts?
Unfortunately, VCR is very much incompatible with capybara-webkit. The fact is that capybara webkit is using webkit, which is in c. Webmock and Fakeweb, which are the basis for VCR, can only be used for Ruby web requests. Making the two work together would likely be a monumental task.
I've solved this problem two ways:
The first (hacky, but valid) is to add a new javascript file to the application that is only included in the test environment. This file stubs out the JS classes which make external web requests. Aside from the pure hackatude of this approach, it requires that every time a new request is added or changed you must change the stubs as well.
The second approach is to route all external requests through my own server, effectively proxying all external requests through my server. This has the huge disadvantage that you have to have an action for everything you want to consume (you could genericize it, with some work). It also suffers from the fact that it could as much as double the time for the request to complete. However, since the requests are now being made by Ruby you can use VCR in all it's glory.
In my situations, approach #2 has been much more to my advantage thanks to the fact that I need ruby to manipulate the data so that I can keep my javascript source-agnostic. I was, however, using approach #1 for quite a while successfully.
I've written a small ruby library (puffing-billy) for rspec+capybara that does exactly this -- it injects a proxy in between your browser and the outside world and allows you to fake responses to specific requests.
Example:
describe 'fetching badges from stackoverflow API' do
it 'should show a nice message when you have no badges' do
# stub some JSONP
proxy.stub('http://api.stackoverflow.com/1.1/users/1/badges',
:jsonp => { :badges => [] })
visit '/my_badges'
page.should have_content("You don't have any badges :(")
end
end
What framework do you recommand for writing simple web applications in ruby, between WebRick, Mongrel and Sinatra ?
I would like to answer in json to requests from a client. I would like to have my own code decoupled from the Http framework as much as possible.
Do you know any other framework ?
I wouldn't recommend using WEBrick, period. You would best be served by a Rack-compatible framework. You could write directly in Rack for speed, but it's really unnecessary since Sinatra is so much more pleasant and still very fast.
You may also want to check out Halcyon. I don't know if it's still maintained, but it's designed for writing APIs that respond in JSON.
WEBrick and Mongrel are servers, not frameworks for building web applications. As such, they have APIs that are lower level and tied to their own idiosyncrasies which makes them a bad place to start if you want to design your web application so that it can run on different servers.
I would look for a framework that builds on Rack, which is the standard base layer for building web apps and web frameworks in Ruby these days.
If you are making something really simple, learning Rack's interface by itself is a good place to start.
E.G., a Rack Application that parses json out of a post request's body and prints it back out prettified.
# in a file named config.ru
require 'json'
class JSONPrettyPrinterPrinter
def call env
request = Rack::Request.new env
if request.post?
object = JSON.parse request.body
[200, {}, [JSON.pretty_generate(object)]]
else
[200, {}, ["nothing to see here"]]
end
end
end
run JSONPrettyPrinterPrinter
you can run it by running rackup in the same dir as the file.
Or, if you want something a bit more high level, you can use sinatra, which looks like this
require 'sinatra'
post '/' do
object = JSON.parse request.body
JSON.pretty_generate(object)
end
Sinatra's README is a good introduction to it's features.
ruby newbie alert! (hey that rhymes :))
I have read the official definition but still come up empty handed. What exactly is it when they say middleware? Is the purpose using ruby with https?
the smallish tutorial at patnaik's blog makes things clearer but how do I do something with it on localhost? I have ruby 1.9.2 installed along with rack gem and mongrel server.
Do I start mongrel first? How?
Just to add a simplistic explanation of Rack (as I feel that is missing):
Rack is basically a way in which a web app can communicate with a web server. The communication goes like this:
The web server tells the app about the environment - this contains mainly what the user sent in as his request - the url, the headers, whether it's a GET or a POST, etc.
The web app responds with three things:
the status code which will be something like 200 when everything went OK and above 400 when something went wrong.
the headers which is information web browsers can use like information on how long to hold on to the webpage in their cache and other stuff.
the body which is the actual webpage you see in the browser.
These two steps more or less can define the whole process by which web apps work.
So a very simple Rack app could look like this:
class MyApp
def call(environment) # this method has to be named call
[200, # the status code
{"Content-Type" => "text/plain", "Content-length" => "11" }, # headers
["Hello world"]] # the body
end
end
# presuming you have rack & webrick
if $0 == __FILE__
require 'rack'
Rack::Handler::WEBrick.run MyApp.new
end
You would do well to search for other questions & answers that make sense to you. Try "Getting Started with Rails" or "Ruby Web Development". A lot of different topics on this site have been devoted to this exact subject, so you might save yourself some trouble there...
Ignoring the specifics of your question for a minute, it seems like you want to learn Ruby and build web apps. Before you start delving into Rack or Mongrel or anything else, you should know that there are 2 well established frameworks that help build Ruby web applications. The first is Ruby on Rails, and the other is Sinatra. There are many others, but these are the most well documented on Stack Overflow and the internet in general.
Check out the following links for some background...
www.rubyonrails.org
SO: building-a-website-best-practice-and-architecture-with-ruby
www.railstutorial.org
SO: learning-ruby-on-rails
If you still have a burning desire to answer your question - "what is rack?", you should follow the same process, and end up at this Stack Overflow Answer:
What is Rack middleware?
Good luck!
Very nice answers yes indeed. For my two cents I'll add this because if you know how to get to the documentation behind the scenes here you will find lots of information as I have it stashed here and by no means is all that I have.
http://myrackapps.herokuapp.com/