Last active
August 29, 2015 14:11
-
-
Save nguyendangminh/6a3d4eb8b0394427ac6f to your computer and use it in GitHub Desktop.
Snippets for Ruby Sinatra
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Spawn a long run process in Sinatra ### | |
require 'sinatra' | |
get '/process' do | |
child_pid = Process.fork do # spawn a long run process | |
tryCitus.setup(config) | |
Process.exit | |
end | |
Process.detach child_pid | |
############################## | |
### Href value for CSS and JS file ### | |
<link href="<%= url('css/bootstrap.min.css') %>" rel="stylesheet"> | |
<script src="<%= url('js/jquery-1.11.1.min.js') %>"></script> | |
############################## | |
### Sinatra i18n ### | |
# i18n/en.yml | |
login: | |
welcome: Please sign in | |
message: | |
successful: Successful! | |
# i18n/jp.yml | |
login: | |
welcome: ログインしてください | |
message: | |
successful: 成功した! | |
# app.rb | |
require 'sinatra' | |
require 'sinatra/r18n' | |
enable :sessions | |
R18n.default_places = './i18n/' | |
R18n.set('en') | |
include R18n::Helpers | |
... | |
session[:locale] = params[:locale] # setting locale | |
... | |
message = t.message.successful # in controller | |
<%= t.login.welcome %> # in views | |
... | |
Note: If your application inherits from Sinatra::Base then also add: | |
class YourApp < Sinatra::Base | |
register Sinatra::R18n | |
############################## | |
### Sinatra - Send file to user ### | |
get '/download/:filename' do |filename| | |
send_file "/path/to/#{filename}", :filename => filename, :type => 'Application/octet-stream' | |
end | |
############################## | |
### Sinatra - Deployment with Thin ### | |
# app.rb | |
class MyApp < Sinatra::Base | |
get '/' do | |
... | |
end | |
... | |
end | |
# server_thin.rb | |
#!/usr/bin/env ruby | |
require 'thin' | |
require_relative 'app.rb' | |
server = ::Thin::Server.new('0.0.0.0', 80, MyApp) | |
server.log_file = "#{File.expand_path(File.dirname(__FILE__))}/log/thin.log" | |
server.pid_file = "#{File.expand_path(File.dirname(__FILE__))}/thin.pid" | |
server.daemonize | |
server.start | |
# Run | |
$ ./server_thin.rb |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment