Search code examples
ruby-on-railsrubyruby-on-rails-3html-entitieshtml-encode

HTMLEntities vs. URI.escape for decoding a string in Ruby


BACKGROUND: I am looking to decode strings that include HTML entities - i.e. "c#" should be converted to "c%23".

I have found the HTMLEntities project to be generally recommended, but have also found what I think is a simpler solution: Using CGI.escape(*string*) or ERB::Util.url_encode(*string*).

QUESTION: Is there any reason why using CGI.escape or ERB::Util.url_encode for this task is a bad idea? If so, how exactly does one implement HTMLEntities in a Rails 3 project - I can't seem to figure it out from the documentation!


Solution

  • I'm not sure about the exact merits of each method. However, if you want to get the htmlentities working you need to add the following to your Gemfile:

    gem 'htmlentities', :git => "https://github.com/threedaymonk/htmlentities.git"
    

    and run:

    bundle install
    

    Then, in your controller:

    class TestController < ApplicationController
    
      def index 
        coder = HTMLEntities.new
        string = "<élan>" # or whatever string you want to manipulate
        @test = coder.encode(string) # => "&lt;élan&gt;"
      end 
    end 
    

    and then do whatever you want with the @test variable - write it out on your view page etc.