Skip to content

Instantly share code, notes, and snippets.

@chendrix
Last active April 12, 2023 00:35
Show Gist options
  • Save chendrix/02be2a4410e8cdbdb83e to your computer and use it in GitHub Desktop.
Save chendrix/02be2a4410e8cdbdb83e to your computer and use it in GitHub Desktop.
Namecheap API
# app/models/namecheap/api.rb
module Namecheap
class Api
def initialize(client_ip)
@client_ip = client_ip
end
def domain_available?(url)
AvailabilityXmlResponse.new(
availablility_api(url).body
).available?
end
private
attr_reader :client_ip
def availablility_api(url_to_check)
@response ||= HTTParty.get(availability_url(url_to_check))
end
def availability_url(url_to_check)
(<<-URL).strip.gsub(/\n/, '')
https://api.namecheap.com/xml.response?
ApiUser=#{ENV['NAMECHEAP_API_USER']}&
ApiKey=#{ENV['NAMECHEAP_API_KEY']}&
UserName=#{ENV['NAMECHEAP_USER_NAME']}&
Command=namecheap.domains.check&
ClientIp=#{client_ip}&
DomainList=#{url_to_check}
URL
end
end
end
# app/models/namecheap/availability_xml_response.rb
module Namecheap
class AvailabilityXmlResponse
def initialize(content)
self.content = content
end
def available?
to_boolean(xml.css('DomainCheckResult')[0].attributes['Available'].value)
end
private
attr_reader :content
def content=(other_content)
@content ||= Nokogiri::XML(other_content)
end
def to_boolean(str)
str == 'true'
end
end
end
# app/models/namecheap/view/domain.rb
module Namecheap
module View
class Domain
def initialize(url, availability)
@url = url
@availaibility = availability
end
def available?
"It looks like the domain—#{url}—#{is_or_is_not} available"
end
private
attr_reader :url, :availability
def is_or_is_not
(availability) ? "is" : "is not"
end
end
end
end
# app/controllers/domains_controller.rb
class DomainsController < ApplicationController
def search
client_ip = request.ip
namecheap = Namecheap::Api.new(client_ip)
url = params[:url]
available = namecheap.domain_available?(params[:url])
@domain = Namecheap::View::Domain.new(url, available)
end
end
# ... rest of gemfile
gem 'httparty'
gem 'nokogiri'
# config/routes.rb
resources :domains, :only => [] do
collection do
get 'search'
end
end
<% # app/views/domains/search.html.erb %>
<%= @domain.available? %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment