Get absolute (base) url in sinatra
A couple things.
set
is a class level method, which means you are modifying the whole app's state with each request- The above is a problem because potentially, the base url could be different on different requests eg
http://foo.com
andhttps://foo.com
or if you have multiple domains pointed at the same app server using DNS
A better tactic might be to define a helper
helpers do
def base_url
@base_url ||= "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}"
end
end
If you need the base url outside of responding to queries(not in a get/post/put/delete block or a view), it would be better to set it manually somewhere.
Is it possible to to rewrite the base URL in Sinatra?
I use a rack middleware for this rack-rewrite and I am quite happy with it :)
use Rack::Rewrite do
rewrite %r{^/\w{2}/utils}, '/utils'
rewrite %r{^/\w{2}/ctrl}, '/ctrl'
rewrite %r{^/\w{2}/}, '/'
end
EDIT:
Not sure if I understand your problem, but here are a config.ru
file
# encoding: utf-8
require './config/trst_conf'
require 'rack-flash'
require 'rack/rewrite'
use Rack::Session::Cookie, :secret => 'zsdgryst34kkufklfSwsqwess'
use Rack::Flash
use Rack::Rewrite do
rewrite %r{^/\w{2}/auth}, '/auth'
rewrite %r{^/\w{2}/utils}, '/utils'
rewrite %r{^/\w{2}/srv}, '/srv'
rewrite %r{^/\w{2}/}, '/'
end
map '/auth' do
run TrstAuth.new
end
map '/utils' do
run TrstUtils.new
end
map '/srv' do
map '/tsk' do
run TrstSysTsk.new
end
map '/' do
run TrstSys.new
end
end
map '/' do
run TrstPub.new
end
and an example Sinatra::Base subclass
# encoding: utf-8
class TrstAuth < Sinatra::Base
# Render stylesheets
get '/stylesheets/:name.css' do
content_type 'text/css', :charset => 'utf-8'
sass :"stylesheets/#{params[:name]}", Compass.sass_engine_options
end
# Render login screen
get '/login' do
haml :"/trst_auth/login", :layout => request.xhr? ? false : :'layouts/trst_pub'
end
# Authentication
post '/login' do
if user = TrstUser.authenticate(params[:login_name], params[:password])
session[:user] = user.id
session[:tasks] = user.daily_tasks
flash[:msg] = {:msg => {:txt => I18n.t('trst_auth.login_msg'), :class => "info"}}.to_json
redirect "#{lang_path}/srv"
else
flash[:msg] = {:msg => {:txt => I18n.t('trst_auth.login_err'), :class => "error"}}.to_json
redirect "#{lang_path}/"
end
end
# Logout
get '/logout' do
session[:user] = nil
session[:daily_tasks] = nil
flash[:msg] = {:msg => {:txt => I18n.t('trst_auth.logout_msg'), :class => "info"}}.to_json
redirect "#{lang_path}/"
end
end
maybe this helps :) full source on github.
How to get request url in ruby Sinatra class context?
Found the answer by my myself. I use a self defined global variable $PATHNAME
which I can use in any context. Combined with the before do
-preprocessor in my main app, I can fill an use the variable.
before do
$PATHNAME=request.path_info
end
class Foo
def build_menu
highlight_menu_entry if $PATHNAME == '/hello-world'
end
end
Setting up Sinatra to run in a subdirectory
This link might be helpful, it explains how to deploy a Sinatra app with Apache using Passenger (mod_rack):
Deploying a Sinatra App with Apache and Phusion Passenger
The part of particular interest to you is the RackBaseURI
option in the virtual host configuration. The official documentation is available here:
Phusion Passenger users guide - Deploying Rack to Sub URI
change sinatras base url for redirects
Ok I finally got it:
in nginx.conf, in the location block insert:
proxy_set_header Host %YOUR_HOST%;
Can I get the base URL of my Rack service outside of a request handler?
I don't believe it's possible for a Rack application can know ahead of time the "mount point". For example, this config.ru
mounts the same app at multiple mount points:
require 'rack'
app = proc { |env|
[200, {'Content-Type' => 'text/plain'}, ['hello, world!']]
}
run Rack::URLMap.new('/myapp' => app,
'/' => app)
Rack also does not provide any standard method that is called at initialization time. I suspect this is because Rack tries to support plain CGI, where a whole Ruby process may be created to handle each request, with the process exiting at each request. In that situation, there isn't much use for an "init" method.
Get full path in Sinatra route including everything after question mark
If you are willing to ignore hash tag in path param this should work(BTW browser would ignore anything after hash in URL)
updated answer
get "/browse/*" do
p "#{request.path}?#{request.query_string}".split("browse/")[1]
end
Or even simpler
request.fullpath.split("browse/")[1]
How to get current path/route in Sinatra?
I believe you are going to want to use the request
object. request.path_info
should give you what you are looking for.
http://www.sinatrarb.com/faq.html#path_info
Related Topics
Passing Headers and Query Params in Httparty
Put Haml Tags Inside Link_To Helper
How to Set an Option as Selected Using Selenium Webdriver (Selenium 2.0) Client in Ruby
How to Replace the Unicode Gem on Ruby 1.9
Ruby Dynamic Classes. How to Fix "Warning: Class Variable Access from Toplevel"
How to Get Attributes That Were Defined Through Attr_Reader or Attr_Accessor
What Ide to Use for Developing in Ruby on Rails on Windows
Expected to Define. When Calling Class Inside a Module
Devise Custom Messages When Validation Fails
Private Class (Not Class Method) in a Ruby Module
How to Filter Parameters in Rails
How to Get the Latest Record from Each Group in Activerecord
How to Install Nokogiri Ruby Gem with Mkmf.Log Saying Libiconv Not Found
In Ruby, How to Check If Method "Foo=()" Is Defined
Maintaining Cookies Between Mechanize Requests
Any Way to Determine Which Object Called a Method