Rails - appending query parameters to existing URL - ruby

I have an application controller method called redirect back or default which is used to redirect users to the page they were requesting after login
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
I would like to be able to optionally add URL parameters (for some analytics tracking) to the url, but am not sure of the best way. I'd like to change the method signature to this
def redirect_back_or_default(default, params=nil)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
and somehow attach the params to the existing URL. Is there a standard ruby or ROR way to do this? I could obviously brute force check to see if there is a query string as part of the URL with regex and manually build the query string, but I was hoping there is an easier standard way of doing this.

From here:
To pass parameters with redirect_to
you simply add them. Like ...
redirect_to :controller => 'another', :action => 'def', :param1 => 'some', :param2 => 'thing', :param => 'else'

standart approach
def redirect_to_back_or_default(default = "/")
back = case request.env["HTTP_REFERER"]
when request.fullpath
default
when nil
default
else
:back
end
redirect_to back
end

Related

Not all methods are getting called Sinatra

I am building a Ruby app using Sinatra and the Twilio api.
Over a phone call to my assigned Twilio number, the user gets prompted to record an audio message. Once that message is recored the user gets redirected to the following route where if the user dials 1 (or anything else), they should get redirected to their feed of msgs, but if the user dials 2, then the user's message gets deleted and should get redirected to a route where they can record a new message.
Here is my route:
get '/playback/handle-recording/:recordingSID' do
if params['Digits'] = '2'
delete(params['recordingSID'])
deletedMsg = "Audio deleted."
getRecord(deletedMsg)
else
getFeed()
end
end
helper methods:
helpers do
def delete(recording)
recording = client().account.recordings.get(recording)
recording.delete
end
def getFeed()
redirect '/feed'
end
def getRecord(appendMsg)
Twilio::TwiML::Response.new do |response|
if appendMsg
response.Say appendMsg
end
response.Say "Record your message."
response.Record :maxLength => '5', :trim => "trim-silence", :playBeep => "true", :action => '/playback', :method => 'get'
end.text
end
end
My issue is that whether the user lands in the "if" or the "else" the first method, getRecord(deletedMsg) is the one that gets called, and not the getFeed().
How can I fix my route so that if the user lands in the else he does get redirected to his feed page and not to the getRecords method.
Are you sure they're actually making it into the else? Ruby won't just randomly not execute what's in there for no good reason.
One thing you may want to look at is you are assigning, not comparing the params value:
if params['Digits'] = '2'
You'll want to do:
if params['Digits'] == '2'
That could definitely lead to some strange behavior in an if statement, like, for instance always executing one path.

redirect with saving url params?

some time ago forum was created in public directory of a rails app. then forum was moved to a sub-domain.
I've created a redirect for 'domain.com/forum' => 'forum.domain.com by editing routes & creating redirect action.
My question is: how may i preserve url params (ex. 'domain.com/forum?thread1&=1' => 'forum.domain.com?thread1=1' & etc.)
My code as follows:
routes.rb:
map.forum '/forum', :controller => "application",
:action => "redirect_to_forum"
application_controller.rb
def redirect_to_forum
redirect_to "http://forum.domain.com"
end
You can try with getting request url in a hash :-> and then try to preserve your parameters,
on the top of the page use
require 'cgi'
and then get the url wherever you want to get it and use it. After getting parameters in hash u can use them to reconstruct your new url.
parameters = CGI::parse(request.url)
parameter will contain the hash of your all parameters.

Adding a querystring to rack-rewrite response

I've got a simple 301 redirect to capture all non .com domains I have registered for my site as follows:
DOMAIN = 'www.mywebsite.com'
use Rack::Rewrite do
r301 %r{.*}, "http://#{DOMAIN}$&", :if => Proc.new {|rack_env|
rack_env['SERVER_NAME'] != DOMAIN && ENV["RACK_ENV"] == 'production'
}
end
I'd like to add a querystring to the response to add the original domain in the format
?utm_source=#{rack_env['SERVER_NAME']}
But can't quite work out how not to crash the server :) Can it be done & retain any original query string?
It's unlikely that anyone will hit any subpages under the main domain, but when I drop the $& from the rewrite, and replace it with my string, it blows up with no errors in the logs...
I think the reason your original code won't work is because rack_env is not available within your second argument as it's a block argument to the third. Does that make sense?
You can however pass a Proc as the second argument of a redirect, so I think something like this should work (partially tested :)
DOMAIN = 'www.mywebsite.com'
ORIGINAL_REQUEST = Proc.new do |match, rack_env|
"#{DOMAIN}?utm_source=#{rack_env['REQUEST_URI']}"
end
use Rack::Rewrite do
r301 %r{.*}, ORIGINAL_REQUEST, :if => Proc.new {|rack_env|
rack_env['SERVER_NAME'] != DOMAIN && ENV["RACK_ENV"] == 'production'
}
end

Instantiating Devise user models manually using contents of params hash

I'm losing my mind trying to figure this out:
There's a registration module which side-steps the main devise registrations controller, and I have to manually instantiate the Devise-generated user model using User.new(...). I'm using a form_tag to submit all of the necessary parameters necessary for User.new(). Here's a truncated version of my code:
def registration_three
#user = User.new(:email => params[:email], :password => params[:password], :password_confirmation => params[:password_confirmation])
#user.save
#user = User.new(:email => 'patlopez#yahoo.com', :password => 'qwertyui', :password_confirmation => 'qwertyui')
#user.save
end
The second #user.save works, but the first one doesn't. params[:email], params[:password], and params[:password_confirmation] certainly exist, according to the print statements in stdout.
Anyone have any ideas?
EDIT:
So I tried changing all of the single-quote strings in the second User.new(...) to double-quote strings like the ones stored in the params hash...and the second instantiation failed as well. So I'm fairly sure that the issue involves double- vs single-quote strings. Anyone know how to convert double-quote strings to single-quote ones? Thanks in advance.
Store your params in variable first then use them in query to avoid quote errors

How can I reduce redirects in my Rails 3 web app?

I'm new to Rails. I'm developing a store builder.
What I want
I want a root level url for each shop.
http://greatsite.com/my-shop-name
My Solution
shop_controller.rb
def show
if params[:url]
#shop_ref = params[:url]
#shop = Shop.where(:url => #shop_ref).first
else
#shop_ref = params[:id]
#shop = Shop.find(#shop_ref)
redirect_to "/" + #shop.url
return
end
if #shop.nil?
render 'show_invalid_shop', :object => #shop_ref and return
end
render 'show' => #shop
end
def create
#shop_url = (0...8).map{65.+(rand(25)).chr}.join.downcase
#shop = Shop.new(:url => #shop_url)
if #shop.save
redirect_to "/" + #shop.url
else
render :action => "new"
end
end
routes.rb
...
resources :shops
match ':url' => 'shops#show', :constraints => { :url => /[a-z|0-9]{4,30}/ }
...
The Problem
Crap Performance. (It's ugly as sin too, of course.)
Every time someone creates a new shop (which is one click from our home page), it creates a new shop and does a redirect. In New Relic, I see this is killing performance - a lot of time is spent in "Request Queuing".
Is there any neater and faster way of achieving what I want?
I'm not sure why the redirects would be causing such a headache, but:
Could you do something like:
Create the shop via an AJAX call.
On a successful create via AJAX render the show view, and return the html "string".
Replace the contents of the page with JS, and use pushstate to update the URL.
Might be useful to look at: http://pjax.heroku.com/
It's not exactly pretty, but if redirects are really that bad it might help?
I wouldn't recommend this, as it violates the REST principle...
But you could have create call/render the show action after it's done it's object creation (just like you do with "new" when it fails). That would eliminate the redirect but still show the same content as if it had.
There's a lot of reasons why you wouldn't want to do this. I'd look for performance improvements in other places first.

Resources