Httparty Json Parsing and Escaping HTML with html_safe

I have been trying to solve this problem today, and seeking for more suggestions than what I discovered. I am using httparty gem to get wp-json date from a wordpress site to display on my Rails application.

Here is my controller that gets the json info:

#app/controllers/connection_controller.rb

require 'httparty'
require 'json'

class ConnectionController < ApplicationController
  respond_to :json

  def index
  end

  def thirty_days
    get_thirty_days
  end

  private

  def query_wordpress_category(wordpress_category)
    @response = HTTParty.get("http://thriveconnection.com/wp-json/posts?filter[category_name]=#{wordpress_category}&filter[order]=date")
  end

  def get_thirty_days
    query_wordpress_category("30-days")
    @thirty_days = JSON.parse(@response.body)
  end

end

Here is my view:

<% @thirty_days.each do |article| %>
  <div class="row">
    <div class="col-md-6">
      <a href="<%= article['link'] %>" target="_blank">
        <img src="<%= article['featured_image']['source'] %>" alt="" class="img-responsive thumbnail" />
      </a>
    </div>
    <div class="col-md-6">
      <strong class="title-font">
        <a href="<%= article['link'] %>" target="_blank">
          <%= article['title'] %>
        </a>
      </strong>

      <span class="small-font">Published Date <%= article['date'] %></span>
      <br /><br />
      <%= article['excerpt'] %>
      <br /><br />
      <a href="<%= article['link'] %>" target="_blank">
        <i class="fa fa-bookmark-o"></i>Read the Article
      </a>
    </div>
  </div><!-- END .row -->
<% end %>

And here is what gets rendered:

Here is my problem, the excerpt from wordpress gets displayed as an html. How can I display that so the HTML tags don’t show up. Also, is there any way I can format the date to mm/dd/yyyy format? I was suggested to use html_safe for escaping the html, but is that xss safe?

You can format the date with something like:

Date.parse("March 20th, 2015").strftime("%m/%d/%Y")

See strftime for more formatting options.

(Keep in mind that mm/dd/yyyy is only used within the US, so may cause confusion if the audience is global).

1 Like

Thanks, worked well!!!