简体   繁体   中英

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 knowing 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM