diff --git a/lib/blnk.rb b/lib/blnk.rb index da442b5..b32de5b 100644 --- a/lib/blnk.rb +++ b/lib/blnk.rb @@ -4,6 +4,7 @@ require 'ostruct' require_relative 'blnk/version' require_relative 'blnk/client' +require_relative 'blnk/resourceable' require_relative 'blnk/ledger' module Blnk diff --git a/lib/blnk/ledger.rb b/lib/blnk/ledger.rb index d046ba0..c7912ab 100644 --- a/lib/blnk/ledger.rb +++ b/lib/blnk/ledger.rb @@ -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 { diff --git a/lib/blnk/resourceable.rb b/lib/blnk/resourceable.rb new file mode 100644 index 0000000..47c9aca --- /dev/null +++ b/lib/blnk/resourceable.rb @@ -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