Class: Rubytoolbox::Api::ResponseWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/rubytoolbox/api/response_wrapper.rb

Overview

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"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ ResponseWrapper

Returns a new instance of ResponseWrapper.



39
40
41
42
43
44
45
# 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

Class Method Details

.field(name, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
# 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

.fieldsObject



34
35
36
# File 'lib/rubytoolbox/api/response_wrapper.rb', line 34

def fields
  @fields ||= []
end

Instance Method Details

#to_hObject



47
48
49
50
51
52
53
# 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