Skip to content

Instantly share code, notes, and snippets.

@ricvillagrana
Created March 20, 2023 17:36
Show Gist options
  • Save ricvillagrana/1a411f1c1eaefe7f6c4507833694b289 to your computer and use it in GitHub Desktop.
Save ricvillagrana/1a411f1c1eaefe7f6c4507833694b289 to your computer and use it in GitHub Desktop.
EasyBroker Property reader
# frozen_string_literal: true
require 'uri'
require 'net/http'
require 'openssl'
require 'json'
class EasyBrokerApi
BASE_URL = 'https://api.stagingeb.com/v1'
def initialize(key)
@key = key
end
# @param page [Integer] Page number
# @param limit [Integer] Number of items per page
# @param block [Proc] Block iterator
# @return [Hash] Response
#
# api = EasyBrokerApi.new('your_api_key_here')
#
# OR
#
# api.properties(page: 1, limit: 20) do |property|
# puts property['title']
# end
# # => "Hermosa Casa en Colima"
def properties(page: 1, limit: 20, &block)
current_page = page
if block_given?
loop do
url = URI("#{BASE_URL}/properties?page=#{current_page}&limit=#{limit}")
response = request(url)
response['content'].each { |property| block.call(property) }
break unless response['pagination']['next_page']
current_page += 1
end
else
url = URI("#{BASE_URL}/properties?page=#{current_page}&limit=#{limit}")
request(url)
end
end
private
def request(url)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
request['accept'] = 'application/json'
request['X-Authorization'] = 'l7u502p8v46ba3ppgvj5y2aad50lb9'
JSON.parse(http.request(request).read_body)
end
end
require 'minitest/autorun'
require_relative 'easy_broker_api'
class EasyBrokerApiTest < Minitest::Test
def setup
@api = EasyBrokerApi.new('your_api_key_here')
@response = @api.properties(page: 1, limit: 20)
end
def test_properties_returns_content
assert_kind_of Array, @response['content']
end
def test_properties_returns_pagination
assert_kind_of Hash, @response['pagination']
end
def test_properties_returns_next_page
assert @response['pagination']['next_page']
end
def test_block_iterator
@api.properties(page: 1, limit: 20) do |property|
assert_kind_of Hash, property
break
end
end
end
# frozen_string_literal: true
API_KEY = 'l7u502p8v46ba3ppgvj5y2aad50lb9'
require_relative 'easy_broker_api'
api = EasyBrokerApi.new(API_KEY)
# We can either read the whole response and iterate over it
# but we would need to manage all the pagination logic
# response = api.properties(page: 1, limit: 10)
# pagination logic
# Or use the block iterator
api.properties(page: 1, limit: 100) do |property|
puts property['title']
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment