我正在制作一个使用 mongomapper 的 Ruby Sinatra 应用程序,我的大部分响应都将采用 JSON 格式。
混乱
现在我遇到了许多与 JSON 有关的不同事情。
- Std-lib 1.9.3
JSON
类:http ://www.ruby-doc.org/stdlib-1.9.3/libdoc/json/rdoc/JSON.html - JSON 宝石: http: //flori.github.io/json/
ActiveSupport
JSON http://api.rubyonrails.org/classes/ActiveSupport/JSON.html因为我使用的是 MongoMapper,它使用ActiveSupport
.
什么有效
我正在使用一种方法来处理响应:
def handleResponse(data, haml_path, haml_locals)
case true
when request.accept.include?("application/json") #JSON requested
return data.to_json
when request.accept.include?("text/html") #HTML requested
return haml(haml_path.to_sym, :locals => haml_locals, :layout => !request.xhr?)
else # Unknown/unsupported type requested
return 406 # Not acceptable
end
end
该行:
return data.to_json
当data
是我的MongoMapper
模型类之一的实例时起作用:
class DeviceType
include MongoMapper::Document
plugin MongoMapper::Plugins::IdentityMap
connection Mongo::Connection.new($_DB_SERVER_CNC)
set_database_name $_DB_NAME
key :name, String, :required => true, :unique => true
timestamps!
end
我怀疑在这种情况下,该to_json
方法来自某个地方ActiveSupport
并在mongomapper
框架中进一步实现。
什么不起作用
我也在使用相同的方法来处理错误。我正在使用的错误类是我自己的错误类之一:
# Superclass for all CRUD errors on a specific entity.
class EntityCrudError < StandardError
attr_reader :action # :create, :update, :read or :delete
attr_reader :model # Model class
attr_reader :entity # Entity on which the error occured, or an ID for which no entity was found.
def initialize(action, model, entity = nil)
@action = action
@model = model
@entity = entity
end
end
当然,当调用to_json
这个类的一个实例时,它是行不通的。不是以一种完全有意义的方式:显然这个方法实际上是定义的。我不知道它会从哪里来。从堆栈跟踪,显然它是activesupport
:
Unexpected error while processing request: object references itself
object references itself
/home/id833541/.rvm/gems/ruby-1.9.3-p392/gems/activesupport-3.2.13/lib/active_support/json/encoding.rb:75:in `check_for_circular_references'
/home/id833541/.rvm/gems/ruby-1.9.3-p392/gems/activesupport-3.2.13/lib/active_support/json/encoding.rb:46:in `encode'
/home/id833541/.rvm/gems/ruby-1.9.3-p392/gems/activesupport-3.2.13/lib/active_support/json/encoding.rb:246:in `block in encode_json'
/home/id833541/.rvm/gems/ruby-1.9.3-p392/gems/activesupport-3.2.13/lib/active_support/json/encoding.rb:246:in `each'
/home/id833541/.rvm/gems/ruby-1.9.3-p392/gems/activesupport-3.2.13/lib/active_support/json/encoding.rb:246:in `map'
/home/id833541/.rvm/gems/ruby-1.9.3-p392/gems/activesupport-3.2.13/lib/active_support/json/encoding.rb:246:in `encode_json'
但是这个方法在我的类中实际定义在哪里?
问题
我需要像这样覆盖我的类中的方法:
# Superclass for all CRUD errors on a specific entity.
class EntityCrudError < StandardError
def to_json
#fields to json
end
end
但我不知道如何进行。鉴于顶部提到的 3 种方式,对我来说最好的选择是什么?