Using Disqus and Ruby on Rails
By Brian Buchalter · Saturday, January 14, 2012
Disqus in a development environment
Before we get started, I'd recommend that you have two Disqus "sites"; one for development and one for production. This will allow you to see real content and experiment with how things will really behave once you're in production. Ideally, your development server would be publicly accessible to allow you to fully use the Disqus moderation interface, but it isn't required. Simply register another Disqus site, and make sure that you have your shortname configured by environment. Feel free to use whatever method you prefer for defining these kinds of application preferences. If you're looking for an easy way, considering checking out my article on Working with Constants in Ruby. It might look something like this:
# app/models/article.rb DISQUS_SHORTNAME = Rails.env == "development" ? "dev_shortname".freeze : "production_shortname".freeze
Each time you load the universal code, you need to specify a few configuration variables so that the correct thread is loaded:
- disqus_shortname: tells Disqus which website account (called a forum on Disqus) this system belongs to.
- disqus_identifier: tells Disqus how to uniquely identify the current page.
- disqus_url: tells Disqus the location of the page for permalinking purposes.
Let's create a Rails partial to set up these variables for us, so we can easily call up the appropriate comment thread.
The above code will populate the div#disqus_thread with the correct content based on your disqus_identifier. By setting up a single partial that will always render your threads, it becomes very easy to adjust this code if needed.
Disqus Identifier Gotcha
Often an index page will want to display a count of how many comments are in a particular thread. Disqus uses the same asynchronous approach to loading comment counts. Comment counts are shown by adding code such as the following where you want to display your count:
# HTML <a href="http://example.com/article1.html#disqus_thread" data-disqus-identifier="<%=@article.id%>"> This will be replaced by the comment count </a> # Rails helper <%= link_to "This will be replaced by the comment count", article_path(@article, :anchor => "disqus_thread"), :"data-disqus-identifer" => @article.id %>
Disqus recommends adding it just before the closing