Ryan Ahearn
Ryan Ahearn

Reputation: 7934

Can I modify DNS settings for a Ruby on Rails app?

I am trying to integrate with a third party service through my Ruby on Rails application that has an address that can only be resolved by some DNS servers.

Is there a way to tell my application which DNS server to do lookups with? Either general Ruby solutions or Heroku specific solutions would be fine.

Upvotes: 4

Views: 2363

Answers (2)

Tema Bolshakov
Tema Bolshakov

Reputation: 1193

You don't need to undefine constants use Resolv::DefaultResolver.replace_resolvers instead:

Resolv::DefaultResolver.replace_resolvers([
  Resolv::Hosts.new, 
  Resolv::DNS.new(
    nameserver: ['8.8.8.8', '8.8.4.4'], 
    search: ['mydns.com'], 
    ndots: 1
  )
])

require 'resolv-replace'

Upvotes: 3

Ryan Ahearn
Ryan Ahearn

Reputation: 7934

Found a way to replace the DNS resolver app-wide.

Create config/initializers/dns.rb with:

class << Resolv

  def use_google_dns
    remove_const :DefaultResolver
    const_set :DefaultResolver, self.new(
      [Resolv::Hosts.new, Resolv::DNS.new(nameserver: ['8.8.8.8', '8.8.4.4'], search: ['mydns.com'], ndots: 1)]
    )
  end

end

Resolv.use_google_dns
require 'resolv-replace'

Tested with Ruby 2.0, but I believe it will also work with 1.9. The file location instruction is Rails specific, but the code should work with any Ruby project.

Upvotes: 6

Related Questions