Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions lib/purple/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,23 @@ def path(name, method: :get, is_param: false)
@parent_path = path.parent
end

def draw(name)
call_site = caller_locations(1, 1).first
raise LoadError, 'Could not detect caller file for draw' if call_site.nil?

caller_file = call_site.absolute_path || call_site.path
raise LoadError, 'Could not detect caller file for draw' if caller_file.nil?

file_name = name.to_s
file_name += '.rb' unless file_name.end_with?('.rb')

route_path = File.expand_path(file_name, File.dirname(caller_file))

raise LoadError, "Your router tried to draw #{route_path}, but the file does not exist" unless File.exist?(route_path)

instance_eval(File.read(route_path), route_path.to_s)
end

def root_method(method_name)
current_path = @parent_path

Expand Down
31 changes: 31 additions & 0 deletions spec/purple/client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,14 @@ class Unipile::Linkedin::PurpleClient < Purple::Client
end
end

class DrawnClient < Purple::Client
domain 'https://example.com'

path :api do
draw 'support/drawn_client/v1'
end
end

RSpec.describe Unipile::Linkedin::PurpleClient do
let(:resource) { double(:resource) }
let(:headers) { {} }
Expand Down Expand Up @@ -207,3 +215,26 @@ class Unipile::Linkedin::PurpleClient < Purple::Client
end
end

RSpec.describe DrawnClient do
let(:connection) { double('connection') }

before do
allow(connection).to receive(:headers=)
allow(Faraday).to receive(:new).and_yield(connection).and_return(connection)
end

describe '.warehouses' do
it 'loads nested paths and root methods from an external file' do
response = instance_double(Faraday::Response,
status: 200,
body: { warehouses: [{ id: 1, name: 'Main' }] }.to_json)

expect(connection).to receive(:get).with('https://example.com/api/v1/warehouses', {}).and_return(response)

result = described_class.warehouses

expect(result.warehouses.first.id).to eq(1)
expect(result.warehouses.first.name).to eq('Main')
end
end
end
16 changes: 16 additions & 0 deletions spec/purple/support/drawn_client/v1.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
path :v1 do
path :warehouses, method: :get do
root_method :warehouses

response :ok do
body(
warehouses: [
{
id: Integer,
name: String
}
]
)
end
end
end
Loading