Creating dynamic fields using ActiveRecord :: Serialization.to_xml

I am wondering how people use AR to_xml () to create non-entity fields (as well as not the attribute of the model you are serializing, but possibly using the process attributes) from the controller.

to_xml seems to offer several options for this.

One of them is the transfer of references to methods for the object on which the action is performed: during the serialization process, these methods are called and their results are added to the generated document. I would like to avoid this path, because some of the generated data, depending on the attributes of the object, may be outside the scope of the model itself - for example, creating a URL for a specific "show" action. In addition, this requires too much forethought. I would just like to modify the resulting document by changing the to_xml code from the controller. I do not want you to have to declare a method in an object.

The same goes for overriding to_xml in every object.

The other two options, apparently, better tune the account: one is passed to procs in the serialization parameters that generate these fields, and the other by passing in the block, which will be the attributes of the objects after serialization. They provide the type of custom peer-to-peer setting I'm looking for, and in addition, their declarations link the area to the controller so that they have access to the same material that the controller runs, but these methods seem critically limited: AFAICT they are not contain references to the serializable object. They contain references to the builder object, and I’m sure that you could analyze in the / proc block and find attributes that have already been serialized and use them, but these are hajis or at least not simple and suboptimal ones.

, , procs/ , .

, , , , , - .

, , , . response_to to_xml /. (, , , AR.)

** 3.29.09 - Rails. , :) https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2373-record-sensitive-procs-for-to_xml

+3
2

Proc ( procs), to_xml. , , Proc :

proc = Proc.new {|options| options[:builder].tag!('reverse-name', options[:object].name.reverse)}
object.to_xml :object => object, :procs => [ proc ]

proc, to_xml, , .

+1

Source: https://habr.com/ru/post/1699087/


All Articles