How to Encode/Decode HTML Entities in Ruby

How do I encode/decode HTML entities in Ruby?

HTMLEntities can do it:

: jmglov@laurana; sudo gem install htmlentities
Successfully installed htmlentities-4.2.4
: jmglov@laurana; irb
irb(main):001:0> require 'htmlentities'
=> []
irb(main):002:0> HTMLEntities.new.decode "¡I'm highly annoyed with character references!"
=> "¡I'm highly annoyed with character references!"

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

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) # => "<élan>"
end
end

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

Ruby unescape HTML string

The CGI library is one option:

require 'cgi'

CGI.unescapeHTML('C:\inetpub\wwwroot\adminWeb')
# => "C:\\inetpub\\wwwroot\\adminWeb"

How to decode HTML entities in JavaScript using in a Ruby on Rails project

Ok, the answer to MY question is:

var curData = <%=raw BuildCompact.getData("ruby", "rubinius", 500).to_json %>;

How to HTML encode/escape a string? Is there a built-in?

The h helper method:

<%=h "<p> will be preserved" %>

Ruby HTML Entity Problem

It looks like HTMLEntities.decode returns a string in UTF-8, and your console is choking on that encoding. You'll have to re-encode your string before passing it to puts.

If you're using Ruby 1.9.2, it looks like the code is fairly straightforward (based on the String and Encoding documentation):

puts coder.decode('°').encode(Encoding.find('<Whatever-Windows-Uses>'))

You might have to try a couple different encodings before you find something your console can understand.

If you're on an older version of Ruby, it looks like the re-encoding is doable through Iconv (see this question - I suspect you're just going in the opposite direction).

Hope this helps!



Related Topics



Leave a reply



Submit