繁体   English   中英

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

[英]How to map routes to modules without the use of multiple Sinatra apps?

我有这个结构:

 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(分析)模块的末尾,我想将请求的每个部分路由到他的特定subModule。 如果要求

'analytics/department'

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

app.get 'participation', &departmentParticipation

我首先想到了使用map 但是如何使用它而不必运行新的或继承Sinatra :: Base对象?

不确定这是否是您所需要的,但是这是我构建模块化Sinatra应用程序的方式:通过use

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

需要'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

最后,在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

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM