Home > Mobile >  Rails Custom Scrubber which *modifies* PermitScrubber default behavior
Rails Custom Scrubber which *modifies* PermitScrubber default behavior

Time:01-10

If one uses Rails::Html::PermitScrubber and doesn't specify a value for tags or attributes it defaults to using reasonable defaults from Loofah::HTML5::Scrub. However, as soon as you set tags or attributes it chooses a completely different code path that ignores those defaults.

I want to start with the default functionality provided by Rails::Html::PermitScrubber (i.e. when tags/attributes aren't specified) and just make a few small changes but looking at the class implementation it seems like I would need to basically copy and reimplement half the PermitScrubber methods just to access that default functionality. And the defaults provided by Loofah::HTML5::Scrub don't seem to be part of any existing Loofah::Scrubber class.

So how do I make minor changes to the default operation of Rails::Html::PermitScrubber without reimplementing half the class? Surely this is a very common use case!

CodePudding user response:

I guess you can just subclass Rails::Html::PermitScrubber and override keep_node? to get needed behavior (not changing code path if tags are present).

The code of original keep_node? is

  def keep_node?(node)
    if @tags
      allowed_node?(node)
    else
      Loofah::HTML5::Scrub.allowed_element?(node.name)
    end
  end

Probably, that is the part that you want to update.

Or, you can monkey-patch the existing class if subclass does not suit your case.

  •  Tags:  
  • Related