【问题标题】:Segregate routes and controller in sinatra在 sinatra 中分离路由和控制器
【发布时间】:2020-04-14 14:56:35
【问题描述】:

目前Sinatra控制器长这样,

class UserController < Sinatra::Base
 get '/' do
  # code goes here
 end
end

我怎样才能让它像Rails

# routes.rb
 get '/user' => 'user_controller#index'

【问题讨论】:

    标签: ruby sinatra


    【解决方案1】:

    你可以做一个创建路由的方法。

    看我做的例子:

    require 'sinatra'
    
    class UserController
      def index
        'UserController -> index!'
      end
    
      def posts
        'UserController -> posts!'
      end
    end
    
    def route_get(url, call)
      controller_class, method = call.split('#')
      controller_class = Object.const_get(controller_class)
    
      Sinatra::Base.get url do
        controller_class.new.send(method)
      end
    end
    
    route_get '/', 'UserController#index'
    route_get '/users', 'UserController#index'
    route_get '/users/posts', 'UserController#posts'
    

    如果你喜欢,你可以为其他方法做HTTP。或者您可以传递其他参数。

    【讨论】:

    • 在这个例子中不需要,因为我在route_get函数中调用了Sinatra::Base
    • controller_class.new 抛出错误,我必须使用新的!而是。
    • 如果这段代码可以将params request从路由传递到控制器就好了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 2023-03-22
    • 2019-12-12
    • 2017-12-16
    相关资源
    最近更新 更多