lib/pipekit/repository.rb in pipekit-0.2.0 vs lib/pipekit/repository.rb in pipekit-1.0.0
- old
+ new
@@ -1,15 +1,14 @@
-class ConfigNotSetError < Exception; end
module Pipekit
module Repository
- def initialize(request = Pipekit::Request.new)
- @request = request
+ def initialize(request = nil)
+ @request = request || Request.new(resource)
end
def all
- request.get("/#{uri}")
+ get
end
# Public: Get all records from Pipedrive by **one** of the record's fields.
#
# options - A Hash with one key-value pair. Key is a field name and values is a field value.
@@ -19,12 +18,15 @@
# where(name: "John Doe")
# where(github_username: "pipedriver")
# where(id: 123)
#
# Returns array of Hashes.
- def where(options)
+ def where(options, raise_error = false)
send("get_by_#{options.keys.first}", options.values.first)
+ rescue ResourceNotFoundError => error
+ raise error if raise_error
+ []
end
# Public: Get the first record by **one** field from Pipedrive.
#
# options - A Hash with one key-value pair. Key is a field name and values is a field value.
@@ -35,11 +37,11 @@
# find_by(github_username: "pipedriver")
# find_by(id: 123)
#
# Returns a Hash or nil if none found.
def find_by(options)
- where(options).first
+ where(options, true).first
end
# Public: Create a record on Pipedrive.
#
# fields - fields for the record.
@@ -48,11 +50,11 @@
#
# create({name: "John Doe", deal_id: 123})
#
# Returns nothing.
def create(fields)
- request.post("/#{uri}", fields)
+ request.post(fields)
end
# Public: Updates a record on Pipedrive.
#
# fields - fields for the record.
@@ -61,19 +63,21 @@
#
# update(123, {name: "Jane Doe"})
#
# Returns nothing.
def update(id, fields)
- request.put("/#{uri}/#{id}", fields)
+ request.put(id, fields)
end
def self.included(base)
- base.send :extend, ClassMethods
+ base.extend(ClassMethods)
end
module ClassMethods
- attr_accessor :uri
+ def resource
+ to_s.split("::").last.tap { |name| name[0] = name[0].downcase }
+ end
end
private
attr_reader :request
@@ -83,20 +87,23 @@
field = method_name.to_s.gsub("get_by_", "")
get_by_field(field: field, value: args[0])
end
+ def get(id = nil)
+ request.get(id)
+ end
+
def get_by_id(id)
- [request.get("/#{uri}/#{id}")]
+ [get(id)]
end
def get_by_field(field:, value:)
- result = request.search_by_field(type: uri, field: field, value: value)
+ result = request.search_by_field(field: field, value: value)
result.map { |item| get_by_id(item["id"]) }.flatten
end
- def uri
- class_name = self.class.to_s.split("::").last
- "#{class_name.downcase}s"
+ def resource
+ self.class.resource
end
end
end