Skip to content

Instantly share code, notes, and snippets.

@netmask
Created June 15, 2024 21:18
Show Gist options
  • Save netmask/6431902b02103ecb711baecbf19c5a65 to your computer and use it in GitHub Desktop.
Save netmask/6431902b02103ecb711baecbf19c5a65 to your computer and use it in GitHub Desktop.
require 'uri'
require 'net/http'
require 'json'
require 'minitest/autorun'
module Easybroker
class Base
def initialize
@base_url = 'https://api.stagingeb.com'
@api_key = 'l7u502p8v46ba3ppgvj5y2aad50lb9' # imaginen que esto esta en el env ENV["API_KEY"]
end
def get(path, params: {})
do_request Net::HTTP::Get, path, params
end
protected
def build_url(path) = URI("#{@base_url}#{path}")
def http(url)
Net::HTTP.new(url.host, url.port).tap do |http|
http.use_ssl = true
end
end
def do_request(type, path, params)
url = build_url(path)
url.query = URI.encode_www_form(params)
request = build_request(type, url)
case http(url).request(request)
in Net::HTTPSuccess => response
JSON.parse(response.body)
in error
raise "Request failed: #{error.message}"
end
end
def build_request(type, url)
type.new(url).tap do |request|
request["content-type"] = 'application/json'
request["X-Authorization"] = @api_key
end
end
end
class Property < Base
def find(id)
get("/v1/properties/#{id}")
end
def page(page: 1, limit: 10)
get("/v1/properties", params: { page:, limit:})
end
end
end
class TestEasybroker < Minitest::Test
def setup
@property = Easybroker::Property.new
end
def test_find
response = { 'id' => 'property_id', 'title' => 'Test Property' }
@property.stub :get, response do
result = @property.find('property_id')
assert_equal response, result
end
end
def test_page
response = { 'content' => [{ 'id' => 'property_id', 'title' => 'Test Property' }] }
@property.stub :get, response do
result = @property.page
assert_equal response, result
end
end
end
result = Easybroker::Property.new.page
result["content"].each { |property| pp property["title"] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment