How do I make link_to open external URLs in a new window?

前端 未结 4 434
抹茶落季
抹茶落季 2021-01-30 14:39

I need to convert a rails 2.3 site so that all external URLs open in a new window. I could go though every call to link_to and add :target => \'_blank\'

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 15:26

    In the end I went with this, in an initialiser:

    module ExternalLinksInNewTabs
      def new_tab_link_to *args, &block
        if block_given?
          options = args.first || {}
          html_options = args[1] || {}
    
          if options.is_a? String
            if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
              html_options[:target] = '_BLANK'
            end
          end
    
          same_tab_link_to options, html_options, &block
        else
          name = args.first
          options = args[1] || {}
          html_options = args[2] || {}
    
          if options.is_a? String
            if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
              html_options[:target] = '_BLANK'
            end
          end
    
          same_tab_link_to name, options, html_options
        end
      end
    
      def self.is_external_link? host, url
        host.sub! /^www\./, ''
        url =~ /^http/i && url !~ /^http:\/\/(www\.)?#{host}/i
      end
    end
    
    module ActionView
      module Helpers
        module UrlHelper
          include ExternalLinksInNewTabs
    
          alias_method :same_tab_link_to, :link_to
          alias_method :link_to, :new_tab_link_to
        end
      end
    end
    

提交回复
热议问题