Last active
August 29, 2015 14:04
-
-
Save sshaw/88372931a538cb3bfd28 to your computer and use it in GitHub Desktop.
Ruby Module to Generate Amazon Affiliate URLs for Products and Searches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "uri" | |
# | |
# Generate Amazon Affiliate URLs for products and searches | |
# | |
# Amazon::AffiliateURL.config do |cfg| | |
# cfg.id = "your-id" # required | |
# cfg.domain = :us # optional, defaults to :us, can be a domain name | |
# cfg.category = "grocery" # optional, default category for search(), | |
# cfg.secure = true # optional, use https scheme or not, defaults to false | |
# end | |
# | |
# puts Amazon::AffiliateURL.search("salt sugar") | |
# puts Amazon::AffiliateURL.search("ipad","computers") | |
# puts Amazon::AffiliateURL.product("B009W8YQ6K") | |
# | |
# By Skye Shaw (https://gist.github.com/sshaw/88372931a538cb3bfd28) | |
# | |
module Amazon | |
module AffiliateURL | |
DOMAINS = { | |
:ca => "amazon.ca", | |
:cn => "amazon.cn", | |
:de => "amazon.de", | |
:fr => "amazon.fr", | |
:jp => "amazon.co.jp", | |
:uk => "amazon.co.uk", | |
:us => "amazon.com" | |
} | |
class << self | |
def config | |
yield settings | |
end | |
alias :configure :config | |
def product(id) | |
URI.join(host, "gp/product/", id, query).to_s | |
end | |
def search(terms, category = settings.category) | |
params = { "field-keywords" => terms } | |
params["url"] = "search-alias=#{category}" if category | |
URI.join(host, "s", query(params)).to_s | |
end | |
private | |
def host | |
name = %(http#{"s" if settings.secure}://) | |
name << domain | |
end | |
def domain | |
option = settings.domain | |
domain = if option.is_a?(Symbol) | |
DOMAINS[option] | |
elsif option.is_a?(String) | |
option | |
end | |
raise ArgumentError, "missing or invalid domain: '#{option}'" unless domain | |
domain | |
end | |
def query(q = {}) | |
"?" << URI.encode_www_form(q.merge(:tag => settings.id)).gsub("+", "%20") | |
end | |
def settings | |
@settings ||= Struct.new(:domain, :secure, :category, :id).new(:us, false) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment