Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"patch" rails render function to edit default options

when I render :xml in rails I always want the :dasherize => false options. Is there a way to set it application wide as the default, without having to modify rails source code of course?

maybe a render function that somehow takes precedence over the first one and then calls it with this option...

like image 316
luca Avatar asked Feb 28 '23 12:02

luca


1 Answers

Doing something like this does have the downside of potentially leading to unexpected behavior when someone else comes to look at your code (i.e. until they spot your overridden method they may wonder why it is behaving like dasherize false when that hasn't been explicitly specified.) That said, in ApplicationController or one of your specific controllers you can override the render method.

e.g. something like:

class MyController < ApplicationController
  def render(options = nil, extra_options = {}, &block)
    options ||= {} # initialise to empty hash if no options specified
    options = options.merge(:dasherize => false) if options[:xml]
    super(options, extra_options, &block)
  end
end

If you want to allow dasherize to still be overridable in your calls to render you can do the Hash merge in the other direction e.g.

options = {:dasherize => false}.merge(options)
like image 173
mikej Avatar answered Mar 11 '23 04:03

mikej