Last Updated: February 25, 2016
·
1.641K
· tjhanley

Using Wordpress with json_api plugin as a CMS for a Rails App

I know that this post seems a bit blasphemous however we want to make content easy to add for content writers and easy to deal with in multiple environments. For ease we are using a Wordpress instance with the json_api plugin added.

This technique is especially helpful with multiple environments. In the past I've had trouble keeping all of our environments in sync with the same content.

I am using the Faraday gem for my HTTP Client and Settings Logic for all my app settings.

routes.rb

get "/:space_type/:title", :to => "articles#show", :as => :space_type, :constraints => { :space_type => /get-advice/ }

articles_controller.rb

class ArticlesController < ApplicationController
  def show
    @content = Rails.cache.fetch("#{params['space_type']}-#{params['title']}") do
      article = Article.new
      article.get_post(params['title'])
    end
    render
  end
end

The @content instance variable is a json object that you can do whatever you want with in your view.

articles.rb

class Article

  def initialize
    @conn = Faraday.new(:url => "#{Settings.content.host}#{Settings.content.api_base}") do |faraday|
      faraday.use FaradayMiddleware::FollowRedirects
      faraday.request  :url_encoded             # form-encode POST params
      faraday.response :logger                  # log requests to STDOUT
      faraday.adapter  :net_http
    end
  end

  def get_post(title)
    response = @conn.get "get_post?slug=#{title}"
    response.body
  end
end

Now requests to myapp.com/get-advice/some-article-from-wordpress will hit our Wordpress and cache the content in our app. This frees up the content writers to work in tools they know and add content to the site nicely.

One of the things that was tripping me up originally was that Wordpress actually does a 301 redirect to the content. I had to make sure that faraday.use FaradayMiddleware::FollowRedirects was added in my initialization block..