Search code examples
ruby-on-railsruby-on-rails-3multiple-domainsdynamic-url

RoR - Fetch blog feed based on requesting domain


I have a Rails application that runs on two domains, domain1 and domain2. Each domain has its own associated blog, domain1blog and domain2blog, respectively. Currently, I have a model that fetches one of the blogs:

require 'rss'
require 'open-uri'

class Blog

BLOG_URL = 'http://feeds.feedburner.com/domain1blog?format=xml'
POST_LIMIT = 2

def self.fetch_entries
  Rails.cache.fetch('blog', expires_in: 10.minutes) do
    posts = []

    begin
      open BLOG_URL do |rss|
        feed = RSS::Parser.parse(rss)
        posts = feed.items.slice 0...POST_LIMIT
      end
    rescue OpenURI::HTTPError
    # Ignore silently.
    end

    posts
  end
end

end

Right now, this model fetches content from domain1blog irrespective of the the domain from which the call is made.

How can I set the BLOG_URL so that it points to domain1blog from domain1 and domain2blog from domain2?


Solution

  • You can

    • Either create Blog entities with a (predefined) url field in your database, meaning that your fetch_entries method will work out of the box (as an instance method though)
    • or extract the domain in the controller, using ActionDispatch::Http::URL.domain