我有一個路由幫助器,它在我的路由文件中的「helpers do」塊中工作正常,但是當我將幫助器移動到helpers.rb文件時,我收到一個錯誤。這裏是助手:Sinatra JSON.parse將幫助器移動到另一個文件時的未定義方法
def processPutRequest(patient_id, request, _class, foreign_key, route_fragment)
p = Patient.find(patient_id)
data = request.body.read
puts 'request body' + data
data = JSON.parse(data)
host_with_port = request.host_with_port
puts 'hash data: ' + data.inspect
saveListData(params[:id], data, _class, foreign_key)
url = {'url' => "http://#{host_with_port}/patients/#{params[:id]}#{route_fragment}"}.to_json
Rack::Response.new(url)
end
這裏是記錄當幫手在路由文件:
request body{"list_data":[{"id":8440,"value":"Removal of ear wax (procedure)"},{"id":9827,"value":"Foreign body in nose (disorder)"}]}
hash data: {"list_data"=>[{"id"=>8440, "value"=>"Removal of ear wax (procedure)"}, {"id"=>9827, "value"=>"Foreign body in nose (disorder)"}]}
當我將它移動到助手文件:
request body{"list_data":[{"id":8440,"value":"Removal of ear wax (procedure)"},{"id":9827,"value":"Foreign body in nose (disorder)"}]}
NoMethodError - undefined method `parse' for Sinatra::JSON:Module:
上午我錯過了很簡單的事情?
編輯,讓調試器工作。 「數據」 request.body.read後routes文件:
"{"list_data":[{"id":8440,"value":"Removal of ear wax (procedure)"},{"id":9827,"value":"Foreign body in nose (disorder)"}]}"
在助手文件:
"{"list_data":[{"id":8440,"value":"Removal of ear wax (procedure)"},{"id":9827,"value":"Foreign body in nose (disorder)"}]}"
所以內容看起來與我。我可以在這兩個文件之間切實地剪切和粘貼這個方法,它在路徑文件中工作正常,在助手文件中未定義的方法解析失敗。我猜我已經以某種方式定義了該模塊不正確,或者有一個丟失或丟失的字符,但RubyMine沒有顯示錯誤,並且該方法至少部分執行,因此該方法正在源代碼中。
完全助手文件:
module Sinatra
module DynFormat
CONTENT_TYPES={'xml' => 'text/xml','json' => 'application/json'}
def dynamicFormat(data,format=params[:format])
content_type CONTENT_TYPES[format], :charset => 'utf-8'
case format
when 'xml'
data.to_xml
when 'json'
data.to_json
end
end
end
helpers DynFormat
module RouteHelpers
def processPutRequest(patient_id, request, _class, foreign_key, route_fragment)
p = Patient.find(patient_id)
data = request.body.read
puts 'request body' + data
data = JSON.parse(data)
host_with_port = request.host_with_port
puts 'hash data: ' + data.inspect
saveListData(params[:id], data, _class, foreign_key)
url = {'url' => "http://#{host_with_port}/patients/#{params[:id]}#{route_fragment}"}.to_json
Rack::Response.new(url)
end
def saveListData(patient_id, list_data, _class, foreign_key)
p = Patient.find(patient_id)
_class = eval _class
list_data = list_data['list_data']
list_data.each do |x|
_class.create(:patient_id => patient_id, foreign_key => x['id'])
end
end
end
helpers RouteHelpers
end
您是否在app.rb中添加了「require」./helpers'「? – scottxu 2014-11-05 05:36:09
是的,helpers.rb中的另一個幫助程序正在工作 – LukeG 2014-11-05 06:05:46
您是否在使用Sinatra contrib中的任何內容?特別是['Sinatra :: JSON'](http://www.sinatrarb.com/contrib/json.html),還是要求所有帶'require'sinatra/contrib/all''的擴展? – matt 2014-11-05 19:49:22