Rails: Why am I getting the wrong link on this pingback? - ruby-on-rails

So I almost have a pingback sender ready for my rails app (people post links to content and donate to them). Almost.
I've borrowed heavily from the code here:
http://theadmin.org/articles/2007/12/04/mephisto-trackback-library/
I modified the slightly for my purposes:
require 'net/http'
require 'uri'
class Trackback
#data = { }
def initialize(link_id)
link = Link.find(link_id)
site = Link.website
if link.nil?
raise "Could not find link"
end
if link.created_at.nil?
raise "link not published"
end
#data = {
:title => link.name,
:excerpt => link.description,
:url => "http:://www.MyApp.org/links/#{link.to_param}/donations/new",
:blog_name => "My App"
}
end
def send(trackback_url)
u = URI.parse trackback_url
res = Net::HTTP.start(u.host, u.port) do |http|
http.post(u.request_uri, url_encode(#data), { 'Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8' })
end
RAILS_DEFAULT_LOGGER.info "TRACKBACK: #{trackback_url} returned a response of #{res.code} (#{res.body})"
return res
end
private
def url_encode(data)
return data.map {|k,v| "#{k}=#{v}"}.join('&')
end
end
Looks like I'm sending links successfully to my wordpress blog but when I look at the link displayed on the trackback I get this: http://www.theurl.com/that/my/browser/iscurrentlypointing/at/http:://www.MyApp.org/links/#{link.to_param}/donations/new"
All I want is the second half of this long string. Don't know why the current location on my browser is sneaking in there.
I've tried this on two of my blogs so it doesn't seem to be problem related to my wordpress installation.
UPDATE: Okay this is a little odd: I checked the page source and it shows the correct link. When I click on it, however, I get directed to the weird link I mentioned above. Is this a Wordpress Issue?

Whoops! Looks like it was just a syntax error. A sneaky double colon
This line
url => "http:://www.MyApp.org/links/#{link.to_param}/donations/new"
Should of course be like this
url => "http://www.MyApp.org/links/#{link.to_param}/donations/new",

Related

Twilio can't find xml on rails

I am integrating twilio click to call into my rails project.
Everything works fine however the url: in my twilio controller cannot be found on heroku. However, it can be found if you navigate to it in a browser. The phone dials but the voice says "Sorry a problem has occurred, good bye." If I change the url to an external xml file it works fine, just doesn't recognize this particular one. So I'm lead to believe that the controller etc works fine.
twillio_controller.rb
def call
#full_phone = current_user.phone
#partial_phone = #full_phone.last(-1)
#connected_number = "+61" + #partial_phone
#client = Twilio::REST::Client.new ##twilio_sid, ##twilio_token
# Connect an outbound call to the number submitted
#call = #client.calls.create(
:from => ##twilio_number,
:to => #connected_number,
:url => 'http://besttradies.herokuapp.com/mytradies/connect.xml', # Fetch instructions from this URL when the call connects
)
#msg = { :message => 'Phone call incoming!', :status => 'ok' }
end
def connect
# Our response to this request will be an XML document in the "TwiML"
# format. Our Ruby library provides a helper for generating one
# of these documents
response = Twilio::TwiML::Response.new do |r|
r.Say 'If this were a real click to call implementation, you would be connected to an agent at this point.', :voice => 'alice'
end
render text: response.text
end
The OP solved in the comments above:
Figured it out. Routes for connect needed to be POST and I also had to
add skip_before_action :verify_authenticity_token to the twilio
controller as it was behind membership doors.

button to save current page in rails 3.2

I need to have a button to save the current web site (just like clicking on "Save as"), I created a method in the controller which works great for any external site (like http://www.google.com) but doesn't work for the sites inside my application, I get a timeout error!. This has no explanation to me :(
Any clue what is the issue?
#CONTROLLER FILE
def save_current_page
# => Using MECHANIZE
agent = Mechanize.new
page = agent.get request.referer
send_data(page.content, :filename => "filename.txt")
end
I tried also Open URI, same problem!
#CONTROLLER FILE
def save_current_page
# => USANDO OPEN URI
send_data(open(request.referer).read, :filename => "filename.txt")
end
I'm using rails 3.2 and ruby 1.9, any help is appreciated, I already spent like 10 hours trying to make it work!!
Rails can only handle one request at a time. It's a never-ending standoff between the two requests - the first request is waiting for the second request, but the second request is waiting for the first request, and therefore you get a Timeout error. Even if you're running multiple instances of the app with Passenger or something, it's a bad idea.
The only way I can think to get around it would be to use conditional statements like so:
referer = URI.parse(request.referer)
if Rails.application.config.default_url_options[:host] == referer.host
content = "via yoursite.com"
else
agent = Mechanize.new
page = agent.get request.referer
content = page.content
end
send_data content, filename: "filename.txt"
A little dirty but it should get around the Timeout problem. As far a getting the actual content of a page from your own site - that's up to you. You could either render the template, grab something from cache, or just ignore it.
A much better solution would be to enqueue this code into something like Resque or Delayed Job. Then the queue could make the request and wait in line to request the page like normal. It would also mean that the user wouldn't have to wait while your application make a remote request, which is dangerous because who knows how long the page will take to respond.
After several hours and lots of other posts I got to a final solution:
Bricker is right in that it is not possible for rails to render more than once in a call, as taken from http://guides.rubyonrails.org/layouts_and_rendering.html "Can only render or redirect once per action"
The site also states "The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the action_name.html.erb template in the controller’s view path and render it."
Then, the solution that worked great for me was to tell the controller to render to a string if a download flag (download=true) was set in :params (I also use request.url to have it working from any view in my application)
View:
= link_to 'Download', request.url+"&downloadexcel=true", :class => 'btn btn-primary btn-block'
Controller:
def acontrolleraction
#some controller code here
if params[:downloadexcel]
save_page_xls
else
# render normally
end
end
def save_page_xls
#TRESCLOUD - we create a proper name for the file
path = URI(request.referer).path.gsub(/[^0-9a-z]/i, '')
query = URI(request.referer).query.gsub(/[^0-9a-z]/i, '')
filename = #project_data['NOMBRE']+"_"+path+"_"+query+".xls"
#TRESCLOUD - we render the page into a variable and process it
page = render_to_string
#TRESCLOUD - we send the file for download!
send_data(page, :filename => filename, :type => "application/xls")
end
Thanks for your tips!

Prawn PDF with Rails mailer?

I have successfully created an email that sends on creation of a Kase, but now I need to attach a PDF that is created on the fly by Prawn and Prawno. Basically when you visit a kase such as application.com/kase/1 you just append the URL with .pdf i.e. application.com/kase/1.
I spent ages getting the PDF to work and look how I wanted, but I can't figure out how to add the PDF to an auto sending email - mainly because I cannot work out how to give it a link as it's auto generated.
Has anyone ever managed to get this to work?
Thanks,
Danny
I suppose it would be better if you store generated pdf somewhere - for caching purposes, etc.
But with current configuration, you can read generated page with Net::HTTP and attach response:
require 'net/http'
def your_mailer_method(record)
#...
attachment "application/pdf" do |a|
a.body = Net::HTTP.get('yourdomain.com', "/kase/#{record.id}.pdf")
a.filename="your_pdf_name.pdf"
end
end
You really should consider just not using Prawnto, and creating a subclass of Prawn::Document to do what you need. Then, in both your controller and your mailer code, it should just be:
MyReport.new.render
See the Prawn documentation on this:
http://wiki.github.com/sandal/prawn/using-prawn-in-rails
For the newer ones, you dont really need to send a request again, when you can ::
mail.attachments["invoice.pdf"] = {:mime_type => "application/pdf" , :content => pdf_generator}
Instead of doing this ::
send_data pdf.render , :filename => file_name_here , :type => "application/pdf"
just do this ::
pdf.render , :filename => file_name_here , :type => "application/pdf"
Do not send_data, just render that pdf in your email attachment as mentioned in the first snippet.
In fact, i just wrote a Gist on github.
This code works for me
def send_file(file, subject, text, to_email)
#subject = subject
#text = text
attachments["#{invoice.invoice_number}.pdf"] = file
from_email = abc#xyz.com
mail(:to => to_email, :from => from_email, :subject=> subject)
end

Rhomobile rhodes Rho AsyncHttp post

I am having problems with Rhomobile rhodes, plaese can someone tell me how to make http post, get, put, and delete using Rho::AsyncHttp?
I've been trying it to no success for hours.
Here's some sample code to place in your controller.rb file
Here's the initial call
def index
Rho::AsyncHttp.get(
:url => 'http://the.page.you.want.to.get',
:callback => (url_for :action => :httpget_callback),
:callback_param => "" )
render :action => :wait
end
the code above will initiate the httpget_callback method (below)
while that goes off and loads the url it'll change the screen and load the wait.erb file
def httpget_callback
if #params['status'] != 'ok'
##error_params = #params
WebView.navigate(url_for :action => :show_error )
else
#html = #params['body']
end
WebView.navigate ( url_for :action => :show_result )
end
Without getting too far into it - the body of the returned page is placed into #html variable
Hope that helps, if you need more help, let me know.
I have a sample of get an post
res = Rho::AsyncHttp.post(:url => 'http://192.168.1.64/WebServiceTest/Service.asmx/Sumar')
#msg= "Sync http call: #{res}"
http://wiki.rhomobile.com/index.php/RhodesConnectToWebServices
I'm often struggling with the nuances of AsyncHttp in Rhodes as well, so I can't claim mastery yet, but I really felt the need to chime in with a suggestion:
I find using the Firebug plugin of Firefox to be VERY helpful when debugging my Rhodes app. You can hook it up very easily! You can load your app with any browser by configuring the web server to run on a specific port. This setting is in rhoconfig.txt and it is called local_server_port.
This is specifically helpful because you can easily survey the HTML and raw data of requests/responses and use the console to run javascript commands and play with the DOM and web page in realtime.

Rails Recaptcha plugin always returns false

I'm using the rails recaptcha plugin found here: http://github.com/ambethia/recaptcha/tree/master
I have signed up for an account on recaptcha.com, obtained a public & private key, and the site is configured with a global key (for now).
In config/environment.rb I setup the environment variables:
ENV['RECAPTCHA_PUBLIC_KEY'] = 'xxxxxxxxxxxxxxxx'
ENV['RECAPTCHA_PRIVATE_KEY'] = 'XXXXXXXXXXXXXXxx'
In my view I render the captcha like this:
<%= recaptcha_tags %>
And in my controller processing this form I have this:
unless verify_recaptcha # <-- always returns false
flash[:error] = "Your captcha entry was invalid"
render :action=>'new'
return
end
My problem is that verify_recaptcha always returns false.
I must be missing something simple, but I don't see it. And before I get a smart-alec reply, YES I'm typing the correct words into the captcha box :)
Just as a note, make sure you didn't accidentally switch around the public and private keys; they are different.
I can't tell if you're already handling the possibility that it is correct, in which case you would want to have something like this:
if verify_recaptcha
#thing.save!
redirect_to success_path
else
flash[:error] = "There was an error with the recaptcha code below. Please re-enter the code and click submit."
render :action => 'new'
end
And remember to use:
<%= recaptcha_tags :ssl => true %>
If you are using SSL.
I went in and looked at the recaptcha plugin. The pertinent part reads something like this:
recaptcha = Net::HTTP.post_form URI.parse("http://#{server}/verify"), {
"privatekey" => private_key,
"remoteip" => request.remote_ip,
"challenge" => challenge,
"response" => response
}
This takes the challenge and response and returns a response. When I tried it with a challenge and response I generated, I got "true\nsuccess". The following lines of code return false if:
answer, error = recaptcha.body.split.map { |s| s.chomp }
unless answer == "true"
Since I got back "true\nsuccess", answer will be "true", and the code should therefore pass.
Can you try sending the response directly using Net::HTTP and seeing what response you get?

Resources