How do I visit a url in rails - ruby-on-rails

Im working on a small project which I need to send a couple of parameters to another server which has a web service for sending of SMS messages. I'm constructing the URL by calling a method on my controller like so,
...
send_sms(number,message)
sms_url = "http://sms-machine.xx.xx/sendsms/" + number + "/" + message
#go to the url above
end
The resulting page will be a delivery message from the server with either a "NO" or "YES" to show if the message was sent. It is important for the users to know if the sms message was sent or not. So my question is how do I visit the sms url. Is there such a go_to_url function in rails?

You can use Ruby's Net::HTTP or the much simpler open-uri functionality, eg:
require 'open-uri'
status = open("http://sms-machine.xx.xx/sendsms/#{number}/#{message}").read
Net:HTTP is loaded by default.

You can use the standard net/http library to make your own HTTP requests: http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html

Related

MVC pattern and RoR or where must that code be placed? [duplicate]

This question already has answers here:
Where do API calls go in a ruby on rails MVC framework project?
(3 answers)
Closed 7 years ago.
My task is to take some data from users. The next part is to make permanent requests to an API of a third party site and to process responses from it. I don't know where this part should be placed: model, controller, or module? The final part of the app will send statuses to users' emails.
Processing user input from an HTTP request is usually done in the controller.
Send a request to the rails server including the user input.
The request will be routed to the appropriate controller action. In the controller action, form an HTTP request to an external API and include the user input in the request using something like RestClient.
Finally, you will send an email to the user and include the request statuses by calling the deliver! method on a mailer class.
Example:
class UsersController < ApplicationController
def controller_action
#user_input = params[:query]
# Build the external API request URI.
# Using www.icd10api.com as an example.
url = Addressable::URI.new(
scheme: "http",
host: "www.icd10api.com",
query_values: {code: #user_input, r: "json", desc: "long"})
# Perform the external request and parse the response
resp = JSON.parse(RestClient.get(url.to_s))
# Finally, deliver the email.
UserMailer.statuses_email(resp).deliver!
# Return status code
render status: 200
end
end
You can always refactor your code into a module, but I only do this if it's used in 3+ locations.
If you're using this as more than a demo app, I would refer to the link in Andrew CP Kelley's comment:
Where do API calls go in a ruby on rails MVC framework project?
References:
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
You also might want to look into concerns if you're using rails 4+:
How to use concerns in Rails 4
I usually wrap it inside a module or a class and place the file into folder
app/models/services/
Here is the folder I place all things are kind of service, e.g. The logic to requests to API and proceed responses from it.

Replying to SMS via Twilio API with Ruby on Rails 4.0

I'm having a tough time understanding Twilio. I've read the docs many many times and still couldn't get my app run. I'm writing a web app in Ruby on Rails (4.0) to get an SMS text from students and print them out on the website.
In the Gemfile I put
gem 'twilio-ruby'
Then I have a controller like this
class TwilioController < ApplicationController
def index
end
def sent_sms
account_sid = "I put my ID here"
auth_token = "I put my auth token here"
twilio_phone_number = "xxxxxxxxx"
message_body = params["Body"]
from_number = params["From"]
#client = Twilio::REST::Client.new(account_sid, auth_token)
#client.account.sms.messages.create(
from: "+1#{twilio_phone_number}",
to: "+1#{from_number}",
body: "Hey there! I got a text from you"
)
end
Now I don't know how to print out those messages gotten from students to the webpage. I spent 2 days on this and still can't figure it out. Also, I don't know what to put in the URL in Twilio account in this screenshot below. I deploy my app to Heroku though. Any advice is appreciated.
https://www.dropbox.com/s/zxbyw6j5te8ipgp/Screen%20Shot%202014-04-12%20at%203.43.18%20PM.png
Twilio evangelist here.
Let me start clarify whats your trying to do. From the code above it looks like you want to receive a text message from your students and then send them back a simple response. You also want to print out the text messages that you've received? Hopefully I've got that right. If I do, lets start with receiving messages and sending a reply.
When a student sends a text message to your Twilio phone number, Twilio will receive that message and make an HTTP request to whatever URL you have set in the Messaging URL. Based on the Rails code in your post, it looks like that URL is going to be something like:
http://[yourdomain].com/Twilio/send_sms
Now, if you want to send a SMS message the student who sent you a message, you just need to generate and return some TwiML containing the <Message> verb from the send_sms function. That would look something like this:
twiml = Twilio::TwiML::Response.new do |r|
r.Message "Hey there! I got a text from you."
end
twiml.text
If you loaded the send_sms route in a browser you should see that your Rails app outputs some TwiML that looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Message>Hey there! I got a text from you.</Message>
</Response>
This code came from the "Replying to an SMS" quickstart which has a ton of great info in it. Another great resource for getting started with receiving text messages using Rails is this fantastic blog post.
OK, so now you've had a bunch of students send some text messages to you and you want to create a page in your Rails app to display them. For this you're going to need to use the REST API. This sample from the docs shows how to use the Ruby helper library to get a list of messages from Twilio. You can pass the list you get back from Twilio to your Rails view where you can loop over it outputting whatever HTML elements you want to use to display the SMS attributes.
Hop that helps.

Twilio post to url with params[:text_response] and params[:phone_number]

I am using ruby 2.0.0 and Rails 4.0.
I am sending a text message out via my rails app to my end user.
When they respond, I want to redirect them to an api call:
www.myapp.com/api/verify_text_response
Within that API call, I want to see what the text message sent from the end user to my url is. Ideally, I would receive a param of "text_response" that I could then do what I wanted to with.
How can I redirect a reply from my end_user to the above url, and capture the phone number it came from as well as the message sent to me in my params? If this isn't possible, how can I use TwiML to do something similar?
End Goal
For what it's worth, this is what I'm trying to accomplish:
I send a text message out - "Would you like to subscribe?"
The end user responds "Yes" or "No".
I change the subscribed attribute on my subscription model to true or false.
I send another text message saying either "You are subscribed." or "You are not subscribed.".
Item's #3 and #4 are based on the user responding "Yes" or "No" in item #2.
The twilio guide here for Ruby is the most useful documentation out there. They recommend using the Twilio gem in your Rails application by adding the twilio-ruby gem to your Gemfile.
All you need to do to is add the following code to one of your controller's actions (the one that is routed to by www.myapp.com/api/verify_text_response:
def receive_text
# Not exactly sure this is the right parameter, but it's easy to test
sender_message = params[:Body]
response = if (sender_message == "Yes")
"You are subscribed."
else
"You are not subscribed."
end
twiml = Twilio::TwiML::Response.new do |r|
r.Message(response)
end
twiml.text
end
To make your Rails application accessible to Twilio, follow the directions found on this page:
Copy and paste the URL of your server into the "SMS" URL of a number
on the Numbers page of your Twilio Account. On the page for that
number, change the Method from "POST" to "GET".
I wasn't exactly sure from looking at the documentation which parameter holds the user's response (I thought it was probably params[:Body]), but the best way to figure out is simply by printing out the parameters that the controller receives when you send a text message to your Twilio number.

Access URL on another website from a model in rails

I want to access a URL of another website from one of my models, parse some information and send it back to my user. Is this possible?
For example, the user sends me an address through a POST, and I want to validate the information through a third party website (USPS or GMaps)
What methods would I use to create the request and parse the response?
This is not a redirect. I want to open a new request that is transparent from the client.
There are a lot of libraries to handle this such as:
HTTParty on http://github.com/jnunemaker/httparty
Curb on http://curb.rubyforge.org/
Patron on http://github.com/toland/patron
Example using Patron:
sess = Patron::Session.new
sess.timeout = 10
sess.base_url = "http://myserver.com:9900"
sess.headers['User-Agent'] = 'myapp/1.0'
resp = sess.get("/foo/bar")
if resp.status < 400
puts resp.body
end
Each solution has its own way of handling requests and parsing them as well as variations in their API. Look for what fits your needs the best.

My web site need to read a slow web site, how to improve the performance

I'm writing a web site with rails, which can let visitors inputing some domains and check if they had been regiestered.
When user clicked "Submit" button, my web site will try to post some data to another web site, and read the result back. But that website is slow for me, each request need 2 or 3 seconds. So I'm worried about the performance.
For example, if my web server allows 100 processes at most, that there are only 30 or 40 users can visit my website at the same time. This is not acceptable, is there any way to improve the performance?
PS:
At first, I want to use ajax reading that web site, but because of the "cross-domain" problem, it doesn't work. So I have to use this "ajax proxy" solution.
It's a bit more work, but you can use something like DelayedJob to process the requests to the other site in the background.
DelayedJob creates separate worker processes that look at a jobs table for stuff to do. When the user clicks submit, such a job is created, and starts running in one of those workers. This off-loads your Rails workers, and keeps your website snappy.
However, you will have to create some sort of polling mechanism in the browser while the job is running. Perhaps using a refresh or some simple AJAX. That way, the visitor could see a message such as “One moment, please...”, and after a while, the actual results.
Rather than posting some data to the websites, you could use an HTTP HEAD request, which (I believe) should return only the header information for that URL.
I found this code by googling around a bit:
require "net/http"
req = Net::HTTP.new('google.com', 80)
p req.request_head('/')
This will probably be faster than a POST request, and you won't have to wait to receive the entire contents of that resource. You should be able to determine whether the site is in use based on the response code.
Try using typhoeus rather than AJAX to get the body. You can POST the domain names for that site to check using typhoeus and can parse the response fetched. Its extremely fast compared to other solutions. A snippet that i ripped from the wiki page from the github repo http://github.com/pauldix/typhoeus shows that you can run requests in parallel (Which is probably what you want considering that it takes 1 to 2 seconds for an ajax request!!) :
hydra = Typhoeus::Hydra.new
first_request = Typhoeus::Request.new("http://localhost:3000/posts/1.json")
first_request.on_complete do |response|
post = JSON.parse(response.body)
third_request = Typhoeus::Request.new(post.links.first) # get the first url in the post
third_request.on_complete do |response|
# do something with that
end
hydra.queue third_request
return post
end
second_request = Typhoeus::Request.new("http://localhost:3000/users/1.json")
second_request.on_complete do |response|
JSON.parse(response.body)
end
hydra.queue first_request
hydra.queue second_request
hydra.run # this is a blocking call that returns once all requests are complete
first_request.handled_response # the value returned from the on_complete block
second_request.handled_response # the value returned from the on_complete block (parsed JSON)
Also Typhoeus + delayed_job = AWESOME!

Resources