diff --git a/lib/purple/client.rb b/lib/purple/client.rb index 6f5336c..c9f68fa 100644 --- a/lib/purple/client.rb +++ b/lib/purple/client.rb @@ -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 diff --git a/spec/purple/client_spec.rb b/spec/purple/client_spec.rb index 5ee4b89..dad9209 100644 --- a/spec/purple/client_spec.rb +++ b/spec/purple/client_spec.rb @@ -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) { {} } @@ -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 diff --git a/spec/purple/support/drawn_client/v1.rb b/spec/purple/support/drawn_client/v1.rb new file mode 100644 index 0000000..6e69912 --- /dev/null +++ b/spec/purple/support/drawn_client/v1.rb @@ -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