如何在不使用多个Sinatra应用程序的情况下将路径映射到模块?

时间:2015-07-13 17:30:19

标签: ruby web routing sinatra

我有这个结构:

 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

在模块分析结束时,我想将每个请求路由到他的特定子模块。如果要求

'analytics/department'

它应该重定向到模块DepartmentLevel,它有自己的路由

app.get 'participation', &departmentParticipation

我首先考虑使用地图。但是如何使用它而不必运行新的或继承Sinatra :: Base对象?

1 个答案:

答案 0 :(得分:1)

不确定这是否是您所需要的,但这里是我如何构建我的模块化Sinatra应用程序:使用use

首先,我有ApplicationController。它是所有其他控制器的基类。它位于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

现在,所有其他控制器/模块都继承自ApplicationController。示例controllers/website_controller.rb

要求&#39; controllers / application_controller&#39;

class WebsiteController < ApplicationController
  helpers WebsiteHelpers

  get('/') { slim :home }
  get('/updates') { slim :website_updates }
  get('/test') { binding.pry; 'foo' } if settings.development?
end

最后,在app.rb中,它们汇集在一起​​:

# 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

使用此安装程序,我需要在config.ru中执行的所有操作

require './app.rb'
run MyApp

希望这有帮助!

相关问题