Route Handlers Inside a Class

后端 未结 2 1553
囚心锁ツ
囚心锁ツ 2020-12-14 22:28

I have a Sinatra app setup where most of the logic is performed inside of various classes, and the post/get routes instantiate those classes and ca

相关标签:
2条回答
  • 2020-12-14 22:54

    You might want to use Sinatra Helpers.

    0 讨论(0)
  • 2020-12-14 23:07

    You just need to inherit from Sinatra::Base:

    require "sinatra/base"
    
    class Example < Sinatra::Base
      def say_hello
        "Hello"
      end
    
      get "/hello" do
        say_hello
      end
    end
    

    You can run your app with Example.run!.


    If you need more separation between parts of your application, just make another Sinatra app. Put shared functionality in model classes and helpers, and run all your apps together with Rack.

    module HelloHelpers
      def say_hello
        "Hello"
      end
    end
    
    class Hello < Sinatra::Base
      helpers HelloHelpers
    
      get "/?" do
        @message = say_hello
        haml :index
      end
    end
    
    class HelloAdmin < Sinatra::Base
      helpers HelloHelpers
    
      get "/?" do
        @message = say_hello
        haml :"admin/index"
      end
    end
    

    config.ru:

    map "/" do
      run Hello
    end
    
    map "/admin" do
      run HelloAdmin
    end
    

    Install Thin, and run your app with thin start.

    0 讨论(0)
提交回复
热议问题