Class: NeverBounce::API::Response::Container

Inherits:
Base
  • Object
show all
Defined in:
lib/never_bounce/api/response/container.rb

Overview

A container with values, by default supports JSON parsing.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#body_hashHash

Container data. Default is JSON-parsed #raw.

Returns:

  • (Hash)


23
24
25
# File 'lib/never_bounce/api/response/container.rb', line 23

def body_hash
  _cache[:body_hash] ||= JSON.parse(require_attr(:raw))
end

#rawString

Raw response body.

Returns:

  • (String)


34
35
36
# File 'lib/never_bounce/api/response/container.rb', line 34

def raw
  _cache[:raw]
end

Class Method Details

.oattr(name, type, *args) ⇒ Symbol (private)

Declare & register an oattr.

oattr :first_name, :scalar    # => :first_name
oattr ...                     # Handled by `Feature::Oattrs`.

Returns:

  • (Symbol)

    name.

See Also:

  • Feature::Oattrs::ClassMethods#oattr


54
55
56
57
58
59
60
61
62
# File 'lib/never_bounce/api/response/container.rb', line 54

def oattr(name, type, *args)
  if type == :scalar
    scalar_oattr(name, *args)
    name.tap { oattrs << name }
  else
    # Handle other types in parent class.
    super
  end
end

.scalar_oattr(name, options = {}) ⇒ Symbol (private)

Build a generic scalar oattr.

scalar_oattr :first_name
scalar_oattr :page, type: :integer
scalar_oattr :total_valid, type: :integer, allow_nil: true

Returns:

  • (Symbol)

Raises:

  • (ArgumentError)


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/never_bounce/api/response/container.rb', line 71

def scalar_oattr(name, options = {})
  o, options = {}, options.dup
  o[k = :allow_nil] = options.include?(k) ? options.delete(k) : false
  o[k = :key] = options.delete(k) || name
  o[k = :type] = options.delete(k) || :any
  raise ArgumentError, "Unknown options: #{options.inspect}" if not options.empty?

  code = []
  code << %{attr_writer :#{name}}

  code << case o[:type]
    when :any
      %{def #{name}; @#{name} ||= body_hash.fetch("#{o[:key]}"); end}
    when :float
      if o[:allow_nil]
        %{
          def #{name}
            @#{name} ||= unless (v = body_hash.fetch("#{o[:key]}")).nil?
              Float(v)
            end
          end
        }
      else
        %{def #{name}; @#{name} ||= Float(body_hash.fetch("#{o[:key]}")); end}
      end
    when :integer
      if o[:allow_nil]
        %{
          def #{name}
            @#{name} ||= unless (v = body_hash.fetch("#{o[:key]}")).nil?
              Integer(v)
            end
          end
        }
      else
        %{def #{name}; @#{name} ||= Integer(body_hash.fetch("#{o[:key]}")); end}
      end
    else
      raise ArgumentError, "Unknown type: #{o[:type].inspect}"
    end

  class_eval code.join(";")

  name
end