[英]Modular Sinatra App: Can I Replace Blocks with Methods?
您是否成功以這種方式重構了Sinatra應用程序?:
require 'sinatra/base'
class UserApp < Sinatra::Base
get '/' do
content_type :json
User.all.to_json
end
get '/:id' do |id|
content_type :json
User.find(id).to_json
end
# etc, etc. (there are many routes)
end
require 'sinatra/base'
require 'user_routes'
class UserApp < Sinatra::Base
register UserRoutes
end
# ----- a separate file -----
module UserRoutes
def list
content_type :json
User.all.to_json
end
def find(id)
content_type :json
User.find(id).to_json
end
def self.registered(app)
app.get '/', &UserRoutes.list # <-- this is the piece I cannot figure out
app.get '/:id', &UserRoutes.find # <-- this is the piece I cannot figure out
# etc, etc. (there are many routes)
end
end
我似乎無法弄清楚如何以這種方式將UserModule的方法傳遞給app.get
,使得這些方法的調用范圍與簡單傳遞一個塊的范圍相同(例如,這些方法如何訪問content_type
和其他Sinatra功能) 。
ruby 2.0.0
這是問題的非常簡化的版本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.