Sha256: 164e141fdf5a354cc1546bdacb9c9f9b0d85bc64ae649503610e7e24d6e4987b

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

module Qismo
  class DataObject
    def initialize(**opt)
      opt.each do |key, value|
        value = if value.is_a?(Array)
          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 Collection < Array
    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

    def has_next_page?
      @next_page != nil
    end

    alias_method :next_page?, :has_next_page?

    def has_prev_page?
      @prev_page != nil
    end

    alias_method :prev_page?, :has_prev_page?

    def next_page
      @next_func.call if has_next_page?
    end

    def prev_page
      @prev_func.call if has_prev_page?
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
qismo-0.8.7 lib/qismo/model.rb