Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I override the default link_to helper?

Yi Mei Wang asked in Rails

I accept a lot of user input links and output them as anchor tags. As a result, I'm worried that there may be cases of users trying to inject Javascript into the href attribute.

I would like to override default link_to so that it sanitizes the output as a default, with an optional parameter to turn off sanitization

Reply

I wouldn't override it, just add your new method and call it like safe_link_to.

Roughly something like this:

def safe_link_to(name = nil, options = nil, html_options = nil, &block)
  link_to(name, options, html_options, &block)
end

Then you can add your call to sanitize in there. I think you'd probably wrap options with the sanitize call most likely.

Reply

Hey Chris, I was contemplating creating a new method, but I decided to override the link_to instead because I did not want the burden for the team to have to constantly remember to use a new method instead of the usual link_to. My intention was to make link_to secure-by-default with the option to turn off sanitization.

I think it works out for us because we don't use javascript: in our href attributes anyway since we consider it bad practice.

After fiddling with it a bunch, I got it to work.

  include ActionView::Helpers::UrlHelper
  alias rails_default_link_to link_to

  def link_to(*args, **kwargs)
    anchor_tag = rails_default_link_to(*args, **kwargs)
    return anchor_tag if kwargs[:keep_dirty]

    sanitize anchor_tag
  end

Then I spent like 2.5 hours trying to publish it as a gem, just to try out what it's like, and now I have my first gem! https://rubygems.org/gems/safe_anchor

Reply

Great! Congrats on your first gem. 🎉

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.