Rails controllers, is it OK to add app code inside of the respond_to format block?
I am wondering if it is considered reasonable to add app code inside of the block passed to format.xxx inside of the respond_to? For example, rails code generator gives us something like:
@object = Object.new
...
... several lines of other app code ...
...
respond_to do |format|
format.xml {render :xml => @object}
end
But, what if I instead do something like this:
respond_to do |format|
format.xml {
@object = Object.new
...
... several lines of other app code ...
...
render :xml => @object
}
end
Is there anything "wrong" or insecure about this approach? Note, I'm not interested in your opinion as to whether or not YOU would do it this way, I'm only interested in kn开发者_StackOverflowowing if there are any downsides or security risks etc. to this approach.
I haven't been working with Rails for that long but I don't see any reason to not put code inside of the block.
Assuming you have more than one format you're responding to, I'd say put any code that is common to more than one format outside the block and put anything specific to that one format inside the block.
For example
@object = Object.new
respond_to do |format|
format.html {
@html_settings = {}
}
format.xml {
@xml_settings = {}
}
}
If you're only responding to the one format then it shouldn't matter where it goes.
精彩评论