class Rubytoolbox::Api::ResponseWrapper

A simple base class for data wrapper objects / structs. Libraries like dry-struct are normally very handy for these things but to keep dependencies minimal we roll our own simple utility here.

Usage:

 class Foo < Rubytoolbox::Api::ResponseWrapper
   field :foo
   field :bar, &:reverse
 end

Foo.new(foo: "foo", bar: "bar").bar # => "rab"

Public Class Methods

field(name, &block) click to toggle source
# File lib/rubytoolbox/api/response_wrapper.rb, line 21
def field(name, &block)
  fields << name.to_s

  block ||= ->(value) { value }

  define_method "#{name}=" do |value|
    instance_variable_set "@#{name}", block.call(value)
  end

  attr_reader name
  private "#{name}="
end
fields() click to toggle source
# File lib/rubytoolbox/api/response_wrapper.rb, line 34
def fields
  @fields ||= []
end
new(data) click to toggle source
# File lib/rubytoolbox/api/response_wrapper.rb, line 39
def initialize(data)
  self.class.fields.each do |name|
    value = data.key?(name.to_s) ? data[name.to_s] : data[name.to_sym]

    send "#{name}=", value unless value.nil?
  end
end

Public Instance Methods

to_h() click to toggle source
# File lib/rubytoolbox/api/response_wrapper.rb, line 47
def to_h
  self.class.fields.each_with_object({}) do |field, hash|
    value = public_send field

    hash[field] = hashify(value)
  end
end

Private Instance Methods

hashify(input) click to toggle source
# File lib/rubytoolbox/api/response_wrapper.rb, line 57
def hashify(input)
  if input.is_a? Array
    input.map { |item| hashify(item) }
  elsif input.is_a? Rubytoolbox::Api::ResponseWrapper
    input.to_h
  else
    input
  end
end