欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

rails中覆盖to_json方法的注意事项

程序员文章站 2024-01-12 09:43:10
...
最近一个项目中,使用到比较多的json,某个model因为一些原因,需要覆盖掉to_json,我简单的通过alias_method做了一个包装,代码如下:
    def to_json_with_ext
      "{\"data\":#{self.to_json_without_ext}}"
    end
    alias_method_chain :to_json, :ext

单元测试没有问题,但运行rails应用时,出现如下异常信息:
wrong number of arguments (1 for 0)

/usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/json/encoding.rb:21:in `to_json'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/json/encoding.rb:21:in `send'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/json/encoding.rb:21:in `encode'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/json/encoding.rb:31:in `raise_on_circular_reference'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/json/encoding.rb:20:in `encode'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/json/encoders/enumerable.rb:10:in `to_json'
/usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/json/encoders/enumerable.rb:10:in `map'


跟踪后发现,activerecord的to_json方法有一个参数options, to_json(options = {}),所以出现参数不匹配的异常,修改代码如下:
    def to_json_with_ext(options = {})
      "{\"data\":#{self.to_json_without_ext(options)}}"
    end
    alias_method_chain :to_json, :ext


运行通过。