Jan Wrobel
Jan Wrobel

Reputation: 7099

What does Ruby 'to' function do?

Pardon the very basic question, but I'm not a Ruby programmer and I need to understand a line of Ruby code:

redirect to('/')

redirect is from Sinatra and I understand what it does, but 'to' is such a common word that however I try to Google this function, I can't find it. Following modules are imported:

require 'cgi'
require 'sinatra'
require 'gollum'
require 'mustache/sinatra'
require 'useragent'
require 'stringex'

And in case it is needed, the whole file or some shorter one that I managed to find.

Upvotes: 1

Views: 185

Answers (4)

jordanpg
jordanpg

Reputation: 6516

The ruby method alias aliases uri to to and performs as advertised in the comment.

# lib/sinatra/base.rb
# Generates the absolute URI for a given path in the app.
# Takes Rack routers and reverse proxies into account.
def uri(addr = nil, absolute = true, add_script_name = true)
  return addr if addr =~ /\A[A-z][A-z0-9\+\.\-]*:/
  uri = [host = ""]
  if absolute
    host << "http#{'s' if request.secure?}://"
    if request.forwarded? or request.port != (request.secure? ? 443 : 80)
      host << request.host_with_port
    else
      host << request.host
    end
  end
  uri << request.script_name.to_s if add_script_name
  uri << (addr ? addr : request.path_info).to_s
  File.join uri
end

alias url uri
alias to uri

Upvotes: 1

Matt Esch
Matt Esch

Reputation: 22966

You can find a lot of information at http://www.sinatrarb.com/intro.html

Browser Redirect

You can trigger a browser redirect with the redirect helper method:

get '/foo' do
  redirect to('/bar')
end

Any additional parameters are handled like arguments passed to halt:

redirect to('/bar'), 303
redirect 'http://google.com', 'wrong place, buddy'

You can also easily redirect back to the page the user came from with redirect back:

get '/foo' do
  "<a href='/bar'>do something</a>"
end

get '/bar' do
  do_something
  redirect back
end

To pass arguments with a redirect, either add them to the query:

redirect to('/bar?sum=42')

Or use a session:

enable :sessions

get '/foo' do
  session[:secret] = 'foo'
  redirect to('/bar')
end

get '/bar' do
  session[:secret]
end

Upvotes: 1

DGM
DGM

Reputation: 26979

It's not a standard ruby function, it is probably a DSL function defined by a framework such as sinatra. Look here:

Upvotes: 1

Mladen Jablanović
Mladen Jablanović

Reputation: 44090

The method is Sinatra::Helpers#uri, and it is aliased (also available) as url and to. It creates an absolute url based on given arguments.

So, nothing but a readable method name provided by Sinatra.

Upvotes: 3

Related Questions