Раздельные маршруты и контролер в синатре - PullRequest
0 голосов
/ 07 апреля 2020

В настоящее время Sinatra контроллер выглядит следующим образом,

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

Как я могу сделать это как Rails

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

1 Ответ

1 голос
/ 08 апреля 2020

Вы можете сделать метод, который создает маршруты.

Смотрите пример, который я сделал:

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. Или вы можете передать другие аргументы.

...