【问题标题】:How to map routes to modules without the use of multiple Sinatra apps?如何在不使用多个 Sinatra 应用程序的情况下将路由映射到模块?
【发布时间】:2015-10-02 02:18:01
【问题描述】:

我有这个结构:

 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 的最后,我想将请求的每个部分路由到他的特定子模块。如果有要求

'analytics/department'

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

app.get 'participation', &departmentParticipation

我首先想到的是使用 ma​​p。但是如何在不必运行新的或继承 Sinatra::Base 对象的情况下使用它呢?

【问题讨论】:

  • 不确定你能不能...你能解释一下为什么地图不适合你吗?
  • @Manuel,map 适合我...但我想工作而不必运行从 Sinatra::Base 继承的新类。经过一段时间的努力,我意识到我可以使用名为@@current_root_path 和@@current_directory_path 的模块变量来简单地管理路由和子路由。通过这个名字,我想你可以明白我的意思......但我也意识到这样做会让我失去可读性。最后,我正在寻找一种类似于您给出的答案的方法:子类化。谢谢! :)

标签: ruby web routing sinatra


【解决方案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

需要“控制器/应用程序控制器”

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

希望这会有所帮助!

【讨论】:

  • 谢谢你,@Manuel。它对我帮助很大!我使用了您的方法,但是在 MyApp 中添加了子路由,例如,这正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多