Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

ruby - Route Handlers Inside a Class

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 call their methods.

I'm thinking about whether putting the post/get route handlers inside of the classes themselves would be a better structure.

In any case, I'd like to know if it is possible. So for instance:

class Example
  def say_hello
    "Hello"
  end

  get '/hello' do
    @message = say_hello
  end
end

Without modification to the above, Sinatra will say there is no method say_hello on the SinatraApplication object.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...