How mix in routes in Sinatra for a better structure

前端 未结 5 874
庸人自扰
庸人自扰 2020-12-13 07:28

I found nothing about how I can mix-in routes from another module, like this:

module otherRoutes
  get \"/route1\" do

  end
end    

class Server < Sinat         


        
5条回答
  •  自闭症患者
    2020-12-13 07:30

    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'
    

提交回复
热议问题