Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 970
Ryan Ahearn Avatar asked Feb 16 '23 05:02

Ryan Ahearn


2 Answers

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.

like image 161
Ryan Ahearn Avatar answered Feb 17 '23 20:02

Ryan Ahearn


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'
like image 27
Tema Bolshakov Avatar answered Feb 17 '23 18:02

Tema Bolshakov