Rhomobile rhodes Rho AsyncHttp post - rhomobile

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.

Related

Upload file to server is going through normal request, while ajax is not working Ruby on Rails

i am currently trying to upload a file with an ajax request on rails. My controller code is (main action):
def changePage
#welcome = WelcomeController.new
respond_to do |format|
format.html
format.js
end
end
My application is single paged, and the pages are changed via ajax requests and everything is working (but i am doint it with link_to, while in this case i use form_for - i do not know if this can be the cause). So in the view (changePage.html.index) i am rendering a partial view (_main.html.slim) which has the following code:
= form_for(:uploaded_file, :remote => true, :url => {:action => 'changePage'}, :html =>
{:multipart=>true}, :authenticity_token => true) do |f|
div class="browse"
span
| Choose file..
= f.file_field :uploaded_file
div id="file-status"
| You have not selected any files yet.
= f.submit :value => "Upload"
So when the Upload button is triggered i end up with a normal request to the server, and not an ajax request (i have changePage.js.erb file). So if someone has some idea about why this is happening it would be nice. {:
Thanks in advance!
For ajax upload you can use gem remotipart.
I am using a javascript plugin File-Uploader . It's simple and works well . I hope it would help you ^_^
You cannot just upload file with an AJAX request, it's technically impossible. So, your options are:
Use normal upload with full page request to keep it simple.
Use ugly hacks e.g. hidden iframe to achieve AJAX-like upload.
Use third-party uploader (there are plenty of them).
I suggest either option #1 or #3, depending on your requirements. #1 if you just need a simple upload, #3 if you need advanced features e.g. multiple files upload, drag & drop upload, chunked upload (for large files) etc.

Rails Controller -- just return the processed data (dont load into a view)

I'm new to Ruby and Rails. I just completed a course in Laravel, so I am aware of the MVC system(not a newbie as far as the basic concepts are concerned).
I have a rather simple question,
I am sending a POST request to my RAILS REST API,the body of the post request contains a json encoded string like this--->
Array ( [method] => POST [timeout] => 45 [redirection] => 5 [httpversion] => 1.0 [blocking] => 1 [headers] => Array ( ) [body] => {"post_content":"here is the post","post_title":"here we are ","post_author":"1"} [cookies] => Array ( ) )
As you can see,its coming from my php based blog.
My rails API is supposed to be taking the post content and automatically adding links to certains words, by comparing the words with some stuff that i have in an SQLite database.
Ok, so my problem is this:
I just want the response from the Rails controller, I dont want anything loaded into a view. The Rails Controller - returns the content, with 'a href' tags around words that are found in my database. This is to be sent back as the response to my post request, and i want to access it directly as the body of the response.
As of now I dont know how this is to be done. Laravel has the ability to 'return' whatever you want to , at the end of the Controller Action, but in Rails, everything seems to want to load into a view.
I have researched some questions here and found one which said 'render :nothing => true',but that renders nothing at all.Here is what my code looks like.
def process
content = params['post_content']
##perform db function and get back the content with the links embedded.
##HOW TO RETURN THIS CONTENT.
end
Personally, I think, i have to use the render_to_string method, but I have no idea how to do this.
Any help is appreciated.
Best Regards,
Richard Madson.
Some options to consider:
Render just the raw string as the http response body:
render :text => content
Render a view without the default surrounding layout:
render :layout => false
In that case your view could just be:
<%= #content %>
Or render the content as json:
render :json => { :content => content }
The question is, what do you want returned? Text? XML? JSON?
I'm going to assume you want JSON back based on the JSON going in.
respond_to do |format|
format.json { render json: #someobject }
end
It might be helpful to see the rest of the controller method.
If I understand correctly believe what you are looking for is
render :text => "response"
there is also - JSON, XML, nothing, js, file, etc - more information here http://guides.rubyonrails.org/layouts_and_rendering.html

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!

How to create a route without an associated View?

I want to create a route such as
get '/referrals/send_invite/:email_address'
I will be calling this route via remote: true and GET. However if I issue the GET request in my browser, the route will still try to find a View, thus leading me to:
Template is missing
Is there a way that I could tell rails that the send_invite method in Referrals Controller doesn't have a view associated?
I would hope that this could be accomplished by just using rails routes.
Thanks.
Not completely sure, but I am guessing you want to start the action send_invite so you are not interested in an actual result, correct?
You could do something like
def send_invite
SomeMailer.mail(:email => params[:email_address])
# or queue it or whatever
head :ok
end
Note that that is not the only option, you could also do something like
render :text => "The mail has been sent to #{params[:email_address]}"
or
render :json => {:result => 'ok', :email_adress => params[:email_address]}
Also note this should be a POST, since this action is not idempotent (a GET should not have side-effects).
Hope this helps.
More likely than not your template missing is coming from not having a sendinvite.js.erb. Try putting a blank one in your view folder to see that sorts it out.

rails how to render a file with correct filename

This is tough one to explain so i'll try my best, and hopefully edit the question if people need more information. I am not providing exact code, but merely an example of the issue.
I am using rails 2.3.8. I am on Unix.
I have a bunch of files under a directory not Apache accessible. (i.e. /data/files/file.rpk)
I have the following in my view.
link_to "RPK File", :controller => 'mycontroller', :action=> 'myaction', :file => '/data/files/file.rpk'
I have the following in my controller.
def myaction
if FileTest.exists?(params[:file])
render :file => params[:file]
end
end
When i select the link on the page i get a download prompt for my desired file, but the name of the file is "myaction" instead of the filename.
Thoughts on how i could get it named correctly?
Sounds like a job for send_file. The x_sendfile option prevents that your workers keep busy while transferring the actual file. You can read more about that in this blogpost.
send_file path_to_file_on_filesystem, :type => "application/zip", :x_sendfile => true
You want to use send_data with the :filename option. See the API documentation.
You want to be extremely careful with this, though. Never ever trust the client/user! They will send file=../../../../etc/group or something in order to read arbitrary files on your system, so be very sure to sanitize that value before passing it to any file-reading methods.

Resources