Skip to content

Commit

Permalink
WIP - abstract some logic into resourceable class
Browse files Browse the repository at this point in the history
  • Loading branch information
devton committed Jun 26, 2024
1 parent 9e965f2 commit 44b2f54
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 33 deletions.
1 change: 1 addition & 0 deletions lib/blnk.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
require 'ostruct'
require_relative 'blnk/version'
require_relative 'blnk/client'
require_relative 'blnk/resourceable'
require_relative 'blnk/ledger'

module Blnk
Expand Down
37 changes: 4 additions & 33 deletions lib/blnk/ledger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,11 @@

module Blnk
# Ledger representation
class Ledger < OpenStruct
include Client
class Ledger < Resourceable
def self.resource_name = :ledgers

def self.find(id)
response = new.get_request(path: "/ledgers/#{id}")
return response unless response.status.success?

new response.parse
end

def self.all
response = new.get_request(path: '/ledgers')
return response unless response.status.success?

response.parse.map do |r|
new r
end
end

def self.create(*)
new(*).save
end

def save
return self if ledger_id

response = post_request(path: '/ledgers', body: body_data)
return response unless response.status.success?

response.parse.each_pair { |k, v| self[k] = v }
self
end

private
def create_args = { name:, meta_data: meta_data || nil }
def persisted? = !ledger_id.nil?

def body_data
{
Expand Down
44 changes: 44 additions & 0 deletions lib/blnk/resourceable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# frozen_string_literal: true

module Blnk
# Resoureable module that bring some tweaks for basic REST api integration
class Resourceable < OpenStruct
include Client

def self.resource_name = raise NotImplementedError

def self.find(id)
response = new.get_request(path: "/#{resource_name}/#{id}")
return response unless response.status.success?

new response.parse
end

def self.all
response = new.get_request(path: "/#{resource_name}")
return response unless response.status.success?

response.parse.map do |r|
new r
end
end

def self.create(**create_args)
new(**create_args).save
end

def save
return self if persisted?

response = post_request(path: "/#{self.class.resource_name}", body: body_data)
return response unless response.status.success?

response.parse.each_pair { |k, v| self[k] = v }
self
end

def create_args = {}
def persisted? = raise NotImplementedError
def body_data = raise NotImplementedError
end
end

0 comments on commit 44b2f54

Please sign in to comment.