How to map routes to modules without the use of multiple Sinatra apps? - ruby

I have this structure:
module Analytics
def self.registered(app)
module DepartmentLevel
departmentParticipation = lambda do
end
departmentStatistics = lambda do
end
app.get '/participation', &departmentParticipation
end
module CourseLevel
courseParticipation = lambda do
end
end
end
And at the end of the module Analytics I would like to route each piece of the request to his specific subModule. If it is requested
'analytics/department'
it should redirect to the module DepartmentLevel which has its own routes as
app.get 'participation', &departmentParticipation
I first thought on using map. But how to use it without having to run a new or inherit Sinatra::Base object?

Not sure if this is what you need, but here's how I build my modular Sinatra apps: By using use
First, I have my ApplicationController. It's the base class for all other Controllers. It lives in controllers/application_controller.rb
class ApplicationController < Sinatra::Base
# some settings that are valid for all controllers
set :views, File.expand_path('../../views', __FILE__)
set :public_folder, File.expand_path('../../public', __FILE__)
enable :sessions
# Helpers
helpers BootstrapHelpers
helpers ApplicationHelpers
helpers DatabaseHelpers
configure :production do
enable :logging
end
end
Now, all other Controllers/Modules inherit from ApplicationController. Example controllers/website_controller.rb:
require 'controllers/application_controller'
class WebsiteController < ApplicationController
helpers WebsiteHelpers
get('/') { slim :home }
get('/updates') { slim :website_updates }
get('/test') { binding.pry; 'foo' } if settings.development?
end
At last, in app.rb is where it all comes together:
# Require some stuff
require 'yaml'
require 'bundler'
Bundler.require
require 'logger'
# Require own stuff
APP_ROOT = File.expand_path('..', __FILE__)
$LOAD_PATH.unshift APP_ROOT
require 'lib/core_ext/string'
require 'controllers/application_controller.rb'
# Some Run-Time configuration...
ApplicationController.configure do
# DB Connections, Logging and Stuff like that
end
# Require ALL models, controllers and helpers
Dir.glob("#{APP_ROOT}/{helpers,models,controllers}/*.rb").each { |file| require file }
# here I glue everything together
class MyApp < Sinatra::Base
use WebsiteController
use OtherController
use ThingController
not_found do
slim :'404'
end
end
With this Setup, all I need to do in config.ru is
require './app.rb'
run MyApp
Hope this helps!

Related

Errno::ENOENT at / no such file or directory

I'm currently working on a sinatra app and im having a little problem.
i'm trying to load my index.erb but sinatra cannot find the index.erb.
Here is my app.rb
require 'rubygems'
require 'sinatra'
module Registration
class HelloWorldApp < Sinatra::Base
get '/' do
erb :index
end
end
end
and this is my Code hierarchy.
It keeps on looking in the directory: Sinatra-Intro/app/views/index.erb
but my views is in the: Sinatra-Intro/views/index.erb
You need to configure your application instance, something like this should work:
require 'rubygems'
require 'sinatra'
module Registration
class HelloWorldApp < Sinatra::Base
configure do
set :public_folder , File.expand_path('../public', __FILE__)
set :views , File.expand_path('../views', __FILE__)
set :root , File.dirname(__FILE__)
set :show_exceptions, development?
# Optional: Load from external file
#YAML.load_file('path/to/config.yml').each do |k, v|
# set(k.to_sym, v)
#end
end
get '/' do
erb :index
end
end
end
Then:
bundle exec rackup
You can change the default location with the view setting. Like this:
set :views, Proc.new { File.join(root, "views") }

How can I use my Sinatra helpers in included modules?

I have my routes and helpers defined in external files and included by Sinatra, however I'm new to Ruby and I can't now figure out how I can use my helper methods in my routes. When I run the code in RubyMine and access a profile URL I get the error "NoMethodError - undefined method `protected!'"
## Main class
require 'sinatra/base'
class MyApp < Sinatra::Base
register Sinatra::MyHelpers
register ProfileRoutes
...
end
## Helpers include
require 'sinatra/base'
module Sinatra
module LocutusHelpers
def self.registered( app )
app.before do
...
end
def protected!
...
end
end
end
end
## Routes include
require 'sinatra/base'
module ProfileRoutes
def self.registered( app )
app.get '/profile/:userid' do
protected!
...
end
end
end
I've tried def self.protected! for the helper but then it cant access the request object.
I've also tried Sinatra::MyHelpers.protected!, Sinatra.protected! and app.protected!, errors are thrown for all of these too
Do you know how I can access the helpers from my routes? Or have I set something up incorrectly?
It looks like you are mixing up adding helpers from extensions and configuring your app from extensions.
You need to move protected! into a module, then when registering your extension add that module as a helpers module.
module LocutusHelpers
# new module, move protected! into here
module HelperMethods
def protected!
...
end
end
def self.registered( app )
# add new hlpers module
app.helpers HelperMethods
# other extension setup as before...
app.before do
...
end
end
end

Modular Sinatra App using Sinatra Reloader?

Hi if I had a 'main' sinatra file with the following code,
require 'sinatra'
require "sinatra/reloader"
class MyApp < Sinatra::Base
configure do
require "./rest/auth.rb"
register Sinatra::Reloader
also_reload '/rest/auth'
end
get '/' do
erb :home
end
end
And I wanted to put my authentication logic inside of /rest/auth.rb, how can I get /rest/auth.rb to reload in development mode? Must I put the configure block and require sinatra/reloader in every one of my controller files? I'd like for my controllers to inherit the settings of my main class. The code inside of auth.rb is as follows:
class MyApp < Sinatra::Base
set(:auth) do |*roles| # <- notice the splat here
condition do
unless logged_in?
session[:success_url] = request.path_info
redirect '/'
end
end
end
def logged_in?
current_user
end
def current_user
if session[:user_id]
u = User.find(:id=>"#{session[:user_id]}")
else
false
end
end
end
I need to restart the server for my changes to take place but I can throw that reload code in auth.rb's configure block though I wouldn't like to. Any ideas?
Try to rewrite like this
require 'sinatra/base'
require "sinatra/reloader"
class MyApp < Sinatra::Base
configure :development do
register Sinatra::Reloader
also_reload './rest/auth'
end
require "./rest/auth.rb"
get '/' do
erb :home
end
end

Reloading models and helpers with Sinatra::Reloader

I'm trying to automatically reload a Sinatra project in JRuby on Windows Vista/7. I'm using Sinatra::Reloader from Sinatra-contrib. Unfortunately, it only seems to work for controllers. Any changes to models and helpers aren't reloaded.
Am I using also_reload incorrectly or something?
Here's what my project looks like:
/app.rb
require 'sinatra'
require 'sinatra/reloader'
require 'json'
class App < Sinatra::Application
enable :sessions
enable :logging
register Sinatra::Reloader
also_reload "models/*.rb"
also_reload "helpers/*.rb"
helpers do
include Rack::Utils
alias_method :h, :escape_html
end
end
require_relative 'helpers/init'
require_relative 'models/init'
require_relative 'controllers/init'
/controllers/init.rb
enable :sessions
require_relative 'auth'
require_relative 'customer'
require_relative 'policy'
require_relative 'forms'
/helpers/init.rb
require_relative 'auth_helper'
require_relative 'customer_helper'
require_relative 'flash_helper'
require_relative 'form_helper'
require_relative 'policy_helper'
/models/init.rb
require 'lib/sqljdbc4.jar'
require 'sequel'
require 'logger'
Java::com.microsoft.sqlserver.jdbc.SQLServerDriver
url = 'foo'
DB = Sequel.connect(url)
DB.loggers << Logger.new($stdout)
Sequel.inflections do |inflect|
inflect.clear :all
end
files = [
:customer,
:customer_email,
:phone_number ]
files.each do |f|
require_relative f.to_s
end
Under current implementation of yours, let's say you change something in helpers/auth_helper.rb. This file gets reloaded but since the helpers/init.rb is unchanged, it won't be reloaded by sinatra-reloader and you won't see the changes. Have you tried shotgun gem?

How mix in routes in Sinatra for a better structure

I found nothing about how I can mix-in routes from another module, like this:
module otherRoutes
get "/route1" do
end
end
class Server < Sinatra::Base
include otherRoutes
get "/" do
#do something
end
end
Is that possible?
You don't do include with Sinatra. You use extensions together with register.
I.e. build your module in a separate file:
require 'sinatra/base'
module Sinatra
module OtherRoutes
def self.registered(app)
app.get "/route1" do
...
end
end
end
register OtherRoutes # for non modular apps, just include this file and it will register
end
And then register:
class Server < Sinatra::Base
register Sinatra::OtherRoutes
...
end
It's not really clear from the docs that this is the way to go for non-basic Sinatra apps. Hope it helps others.
You could do this:
module OtherRoutes
def self.included( app )
app.get "/route1" do
...
end
end
end
class Server < Sinatra::Base
include OtherRoutes
...
end
Unlike Ramaze, Sinatra's routes are not methods, and so cannot use Ruby's method lookup chaining directly. Note that with this you can't later monkey-patch OtherRoutes and have the changes reflected in Server; this is just a one-time convenience for defining the routes.
I prefer the use of sinatra-contrib gem to extend sinatra for cleaner syntax and shared namespace
# Gemfile
gem 'sinatra', '~> 1.4.7'
gem 'sinatra-contrib', '~> 1.4.6', require: 'sinatra/extension'
# other_routes.rb
module Foo
module OtherRoutes
extend Sinatra::Extension
get '/some-other-route' do
'some other route'
end
end
end
# app.rb
module Foo
class BaseRoutes < Sinatra::Base
get '/' do
'base route'
end
register OtherRoutes
end
end
sinata-contrib is maintained alongside the sinatra project
Well you can also use the map method to map routes to your sinatra apps
map "/" do
run Rack::Directory.new("./public")
end
map '/posts' do
run PostsApp.new
end
map '/comments' do
run CommentsApp.new
end
map '/users' do
run UserssApp.new
end
Just my two cents:
my_app.rb:
require 'sinatra/base'
class MyApp < Sinatra::Base
set :root, File.expand_path('../', __FILE__)
set :app_file, __FILE__
disable :run
files_to_require = [
"#{root}/app/helpers/**/*.{rb}",
"#{root}/app/routes/**/*.{rb}"
]
files_to_require.each {|path| Dir.glob(path, &method(:require))}
helpers App::Helpers
end
app/routes/health.rb:
MyApp.configure do |c|
c.before do
content_type "application/json"
end
c.get "/health" do
{ Ruby: "#{RUBY_VERSION}",
Rack: "#{Rack::VERSION}",
Sinatra: "#{Sinatra::VERSION}"
}.to_json
end
end
app/helpers/application.rb:
module App
module Helpers
def t(*args)
::I18n::t(*args)
end
def h(text)
Rack::Utils.escape_html(text)
end
end
end
config.ru:
require './my_app.rb'

Resources