Class: Taxjar::Base

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Memoizable
Defined in:
lib/taxjar/base.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Base

Returns a new instance of Base.



74
75
76
# File 'lib/taxjar/base.rb', line 74

def initialize(attributes = {})
  @attrs = set_attributes(attributes)
end

Instance Attribute Details

#attrsObject (readonly) Also known as: to_h

Returns the value of attribute attrs.



32
33
34
# File 'lib/taxjar/base.rb', line 32

def attrs
  @attrs
end

Class Method Details

.attr_reader(*attrs) ⇒ Object



44
45
46
47
48
49
# File 'lib/taxjar/base.rb', line 44

def attr_reader(*attrs)
  attrs.each do |attr|
    define_attribute_method(attr)
    define_predicate_method(attr)
  end
end

.define_attribute_method(key1, klass = nil, key2 = nil) ⇒ Object



56
57
58
59
60
61
62
63
64
# File 'lib/taxjar/base.rb', line 56

def define_attribute_method(key1, klass = nil, key2 = nil)
  define_method(key1) do
    if attr_falsey_or_empty?(key1)
    else
      klass.nil? ? @attrs[key1] : klass.new(attrs_for_object(key1, key2))
    end
  end
  memoize(key1)
end

.define_predicate_method(key1, key2 = key1) ⇒ Object



66
67
68
69
70
71
# File 'lib/taxjar/base.rb', line 66

def define_predicate_method(key1, key2 = key1)
  define_method(:"#{key1}?") do
    !attr_falsey_or_empty?(key2)
  end
  memoize(:"#{key1}?")
end

.object_attr_reader(klass, key1, key2 = nil) ⇒ Object



51
52
53
54
# File 'lib/taxjar/base.rb', line 51

def object_attr_reader(klass, key1, key2 = nil)
  define_attribute_method(key1, klass, key2)
  define_predicate_method(key1)
end

Instance Method Details

#[](method) ⇒ Object



78
79
80
81
82
83
# File 'lib/taxjar/base.rb', line 78

def [](method)
  warn "#{Kernel.caller.first}: [DEPRECATION] #[#{method.inspect}] is deprecated. Use ##{method} to fetch the value."
  send(method.to_sym)
rescue NoMethodError
  nil
end

#map_collection(klass, key) ⇒ Object



36
37
38
39
40
# File 'lib/taxjar/base.rb', line 36

def map_collection(klass, key)
  Array(@attrs[key.to_sym]).map do |entity|
    klass.new(entity)
  end
end