ruby 通过多个文件将Sinatra用于大型项目

rkue9o1l  于 2023-05-28  发布在  Ruby
关注(0)|答案(8)|浏览(183)

似乎在Sinatra中所有的路由处理程序都被写进一个文件中,如果我理解正确的话,它就像一个大/小控制器。有没有办法把它分割成单独的独立文件,比如说有人调用“/”--一个动作被执行,如果收到类似“/posts/2”的东西,那么另一个动作--类似PHP中应用的逻辑?

chy5wohz

chy5wohz1#

这里是我使用的Sinatra应用程序的基本模板。(我的大型应用程序有200多个这样的文件,不包括供应商的gem,覆盖75-100个显式路由。其中一些路由是覆盖另外50多个路由模式的Regexp路由。)使用Thin时,您可以使用以下命令运行这样的应用程序:
thin -R config.ru start

编辑:我现在维护自己的Monk backbone ,基于下面的 * Riblits *。要使用它来复制我的模板作为您自己项目的基础:

# Before creating your project
monk add riblits git://github.com/Phrogz/riblits.git

# Inside your empty project directory
monk init -s riblits

文件布局:

config.ru
app.rb
helpers/
  init.rb
  partials.rb
models/
  init.rb
  user.rb
routes/
  init.rb
  login.rb
  main.rb
views/
  layout.haml
  login.haml
  main.haml

config.ru

root = ::File.dirname(__FILE__)
require ::File.join( root, 'app' )
run MyApp.new

app.rb

# encoding: utf-8
require 'sinatra'
require 'haml'

class MyApp < Sinatra::Application
  enable :sessions

  configure :production do
    set :haml, { :ugly=>true }
    set :clean_trace, true
  end

  configure :development do
    # ...
  end

  helpers do
    include Rack::Utils
    alias_method :h, :escape_html
  end
end

require_relative 'models/init'
require_relative 'helpers/init'
require_relative 'routes/init'

helpers/init.rb

# encoding: utf-8
require_relative 'partials'
MyApp.helpers PartialPartials

require_relative 'nicebytes'
MyApp.helpers NiceBytes

helpers/partials.rb

# encoding: utf-8
module PartialPartials
  def spoof_request(uri,env_modifications={})
    call(env.merge("PATH_INFO" => uri).merge(env_modifications)).last.join
  end

  def partial( page, variables={} )
    haml page, {layout:false}, variables
  end
end

helpers/nicebytes.rb

# encoding: utf-8
module NiceBytes
  K = 2.0**10
  M = 2.0**20
  G = 2.0**30
  T = 2.0**40
  def nice_bytes( bytes, max_digits=3 )
    value, suffix, precision = case bytes
      when 0...K
        [ bytes, 'B', 0 ]
      else
        value, suffix = case bytes
          when K...M then [ bytes / K, 'kiB' ]
          when M...G then [ bytes / M, 'MiB' ]
          when G...T then [ bytes / G, 'GiB' ]
          else            [ bytes / T, 'TiB' ]
        end
        used_digits = case value
          when   0...10   then 1
          when  10...100  then 2
          when 100...1000 then 3
          else 4
        end
        leftover_digits = max_digits - used_digits
        [ value, suffix, leftover_digits > 0 ? leftover_digits : 0 ]
    end
    "%.#{precision}f#{suffix}" % value
  end
  module_function :nice_bytes  # Allow NiceBytes.nice_bytes outside of Sinatra
end

models/init.rb

# encoding: utf-8
require 'sequel'
DB = Sequel.postgres 'dbname', user:'bduser', password:'dbpass', host:'localhost'
DB << "SET CLIENT_ENCODING TO 'UTF8';"

require_relative 'users'

models/user.rb

# encoding: utf-8
class User < Sequel::Model
  # ...
end

routes/init.rb

# encoding: utf-8
require_relative 'login'
require_relative 'main'

routes/login.rb

# encoding: utf-8
class MyApp < Sinatra::Application
  get "/login" do
    @title  = "Login"
    haml :login
  end

  post "/login" do
    # Define your own check_login
    if user = check_login
      session[ :user ] = user.pk
      redirect '/'
    else
      redirect '/login'
    end
  end

  get "/logout" do
    session[:user] = session[:pass] = nil
    redirect '/'
  end
end

routes/main.rb

# encoding: utf-8
class MyApp < Sinatra::Application
  get "/" do
    @title = "Welcome to MyApp"        
    haml :main
  end
end

views/layout.haml

!!! XML
!!! 1.1
%html(xmlns="http://www.w3.org/1999/xhtml")
  %head
    %title= @title
    %link(rel="icon" type="image/png" href="/favicon.png")
    %meta(http-equiv="X-UA-Compatible" content="IE=8")
    %meta(http-equiv="Content-Script-Type" content="text/javascript" )
    %meta(http-equiv="Content-Style-Type" content="text/css" )
    %meta(http-equiv="Content-Type" content="text/html; charset=utf-8" )
    %meta(http-equiv="expires" content="0" )
    %meta(name="author" content="MeWho")
  %body{id:@action}
    %h1= @title
    #content= yield
ghhaqwfi

ghhaqwfi2#

当然。要查看一个例子,我建议下载Monk gem,如下所述:
https://github.com/monkrb/monk
你可以通过rubygems.org进行gem安装。一旦你有了gem,使用上面链接的说明生成一个示例应用程序。
请注意,除非您愿意,否则您不必在实际开发中使用Monk(实际上,我认为它可能不是最新的)。重点是看看如何轻松地以MVC风格构建应用程序(使用单独的类似控制器的路由文件)。
如果你看看Monk是如何处理它的,这是非常简单的,主要是要求文件在单独的目录中,类似于(你必须定义root_path):

Dir[root_path("app/**/*.rb")].each do |file|
    require file
end
pjngdqdw

pjngdqdw3#

在谷歌上搜索“Sinatra样板”,了解其他人如何布局他们的Sinatra应用程序。从那里你可能会找到一个适合你的需要或简单地使自己的。这不难做到当您开发更多的Sinatra应用程序时,您可以添加到样板文件中。
以下是我制作并用于所有项目的内容:
https://github.com/rziehl/sinatra-boilerplate

zphenhs4

zphenhs44#

我知道这是一个古老的查询,但我仍然不能相信没有人提到Padrino你可以使用它作为一个框架上的Sinatra,或零碎地添加只感兴趣的宝石。它踢了十个屁股!

gxwragnw

gxwragnw5#

对于大型项目来说,Sinatra模块化的关键是学习使用底层工具。
SitePoint有一个非常good tutorial,你可以从那里看到模块化的Sinatra应用程序和助手。但是,你应该特别注意一个重要的细节。您保留多个Sinatra应用程序并使用Rackup挂载它们。一旦你知道如何编写一个基本的应用程序,看看该教程的config.ru文件,并观察他们如何安装独立的Sinatra应用程序。
一旦你学会了用Rack运行Sinatra,一个全新的模块化策略世界就会打开。这显然邀请尝试一些真正有用的东西:现在,您可以依赖于为每个子应用程序提供单独的Gem,这可能使您能够轻松地对模块进行版本控制。
不要低估为你的应用使用gem模块的力量。您可以在一个界限分明的环境中轻松地测试实验性更改并轻松地部署它们。如果出了什么问题,同样很容易恢复。
有一千种方法来组织你的代码,所以尝试一个类似于Rails的布局不会有什么坏处。然而,也有一些关于如何自定义自己的结构的great posts。这篇文章涵盖了大多数Web开发人员的其他常见需求。
如果你有时间,我鼓励你学习更多关于Rack的知识,这是任何基于Ruby的Web应用程序的共同基础。它可能对你如何工作的影响要小得多,但是大多数人在他们的应用程序上执行的某些任务总是更适合作为Rack中间件。

dojqjjoe

dojqjjoe6#

我在同一个站点上托管不同项目的方法是以这样的方式使用sinatra/namespace

server.rb

require "sinatra"
require "sinatra/namespace"

if [ENV["LOGNAME"], ENV["USER"]] == [nil, "naki"]
    require "sinatra/reloader"
    register Sinatra::Reloader
    set :port, 8719
else
    set :environment, :production
end

for server in Dir.glob "server_*.rb"
    require_relative server
end

get "/" do
    "this route is useless"
end

server_someproject.rb

module SomeProject
    def self.foo bar
       ...
    end
    ...
end

namespace "/someproject" do
    set :views, settings.root
    get "" do
        redirect request.env["REQUEST_PATH"] + "/"
    end
    get "/" do
        haml :view_someproject
    end
    post "/foo" do
        ...
        SomeProject.foo ...
    end
end

view_someproject.haml

!!!
%html
    ...

我使用的另一个关于子项目的细节是将它们的名称,描述和路由添加到某种全局变量中,"/"使用该变量来制作指南主页,但我现在没有片段。

yacmzcpb

yacmzcpb7#

阅读这里的文档:
Sinatra Extensions
看起来Sinatra允许你将你的应用程序分解成Ruby模块,这些模块可以通过Sinatra的“register”方法或“helpers”方法拉入,如下所示:

helpers.rb

require 'sinatra/base'

module Sinatra
  module Sample
    module Helpers

      def require_logged_in()
        redirect('/login') unless session[:authenticated]
      end

    end
  end
end

routing/foos.rb

require 'sinatra/base'

module Sinatra
  module Sample
    module Routing
      module Foos

        def self.registered(app)           
          app.get '/foos/:id' do
            # invoke a helper
            require_logged_in

            # load a foo, or whatever
            erb :foos_view, :locals => { :foo => some_loaded_foo }
          end   
        end  

      end
    end     
  end
end

app.rb

#!/usr/bin/env ruby

require 'sinatra'

require_relative 'routing/foos'

class SampleApp < Sinatra::Base

  helpers Sinatra::Sample::Helpers

  register Sinatra::Sample::Routing::Foos

end
eivgtgni

eivgtgni8#

当Monk不为我工作时,我开始自己制作模板。
如果你仔细想想,捆绑一组文件并没有什么特别之处。在2011年初的RedDotRubyConf会议上,他们向我解释了僧侣的哲学,他们特别告诉我,使用它真的是可选的,特别是现在它几乎没有维护。
对于那些想要使用ActiveRecord的人来说,这是一个很好的开始:
简单的Sinatra MVC
https://github.com/katgironpe/simple-sinatra-mvc

相关问题