# frozen_string_literal: true module Qismo # Class to handle http response body # class SingleObject # Initiate data object # # @param opt [Hash] def initialize(opt = {}) opt.each do |key, value| value = if value.is_a?(Array) CollectionObject.new(handle_array(value)) elsif value.is_a?(Hash) self.class.new(value) elsif value.is_a?(TrueClass) || value.is_a?(FalseClass) self.class.define_method("#{key.to_s.delete_prefix("is_")}?".to_sym) { value } value else value end self.class.attr_reader(key.to_sym) instance_variable_set("@#{key}", value) end end def inspect inspected_func ||= -> do attributes = instance_variables.map do |iv| "#{iv.to_s.delete_prefix("@")}=#{instance_variable_get(iv).inspect}" end "#<#{self.class.name} #{attributes.join(", ")}>" end inspected_func.call end alias_method :to_s, :inspect private def handle_array(values) values.map do |value| if value.is_a?(Hash) self.class.new(value) else value end end end end # Class to handle response body that contain pagination # class CollectionObject < Array # Initiate collection # # @param data [Qismo::SingleObject] # @param prev_page [String, Integer] # @param next_page [String, Integer] # @param prev_func [Proc, NilClass] # @param next_func [Proc, NilClass] def initialize(data = [], prev_page: nil, next_page: nil, prev_func: -> { nil }, next_func: -> { nil }) super(data) @prev_page = prev_page @next_page = next_page @prev_func = prev_func @next_func = next_func end # @return [TrueClass, FalseClass] def has_next_page? @next_page != nil end alias_method :next_page?, :has_next_page? # @return [TrueClass, FalseClass] def has_prev_page? @prev_page != nil end alias_method :prev_page?, :has_prev_page? # Call api request for next page # # @return [Qismo::SingleObject, Qismo::CollectionObject] def next_page @next_func.call if has_next_page? end # Call api request for previous page # # @return [Qismo::SingleObject, Qismo::CollectionObject] def prev_page @prev_func.call if has_prev_page? end end end