使用选项配置块进行序列化

Tro*_*ron 8 ruby-on-rails ruby-on-rails-plugins

我在rails项目中使用了serialize_with_options(http://www.viget.com/extend/simple-apis-using-serializewithoptions/),并且已根据链接页面上的示例使用命名块进行渲染:

class Speaker < ActiveRecord::Base
  # ...

  serialize_with_options do
    methods   :average_rating, :avatar_url
    except    :email, :claim_code
    includes  :talks
  end

  serialize_with_options :with_email do
    methods   :average_rating, :avatar_url
    except    :claim_code
    includes  :talks
  end

end
Run Code Online (Sandbox Code Playgroud)

然后我可以使用@ speaker.to_xml(:with_email)调用第二个块配置.这很好用,但是,当我有一个对象数组时,我想弄清楚如何调用这个块.例如,以下内容不起作用:

@speakers = Speaker.all
@speakers.to_xml(:with_email)
Run Code Online (Sandbox Code Playgroud)

返回"TypeError:can not dup Symbol"错误.这对我来说很有意义,因为Array尚未配置为使用serialize_with_options.如何在运行.to_xml并渲染所有发言者时将此标记传递给各个发言人对象:with_email?

Rog*_*ger 1

在上面的示例中,@speakers 是一个 Array 对象。您需要在那里实现/覆盖 to_xml 。那我应该工作:

class Array
    def to_xml (with_email)
        self.each do |element|
            element.to_xml(with_email)
        end
    end
end
Run Code Online (Sandbox Code Playgroud)