Class: A2A::Models::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_a2a/models/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**kwargs) ⇒ Base

Returns a new instance of Base.



59
60
61
62
63
64
# File 'lib/simple_a2a/models/base.rb', line 59

def initialize(**kwargs)
  self.class.attributes.each do |name, opts|
    val = kwargs.key?(name) ? kwargs[name] : resolve_default(opts[:default])
    send(:"#{name}=", val)
  end
end

Class Method Details

.attribute(name, type: nil, default: nil, required: false) ⇒ Object



7
8
9
10
# File 'lib/simple_a2a/models/base.rb', line 7

def attribute(name, type: nil, default: nil, required: false)
  attributes[name] = { type: type, default: default, required: required }
  attr_accessor name
end

.attributesObject



12
13
14
# File 'lib/simple_a2a/models/base.rb', line 12

def attributes
  @attributes ||= {}
end

.from_hash(hash) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/simple_a2a/models/base.rb', line 21

def from_hash(hash)
  return nil if hash.nil?
  kwargs = {}
  attributes.each do |name, opts|
    val = find_value(hash, name)
    next if val.nil?
    kwargs[name] = coerce(val, opts[:type])
  end
  new(**kwargs)
end

.inherited(subclass) ⇒ Object



16
17
18
19
# File 'lib/simple_a2a/models/base.rb', line 16

def inherited(subclass)
  super
  subclass.instance_variable_set(:@attributes, attributes.dup)
end

Instance Method Details

#==(other) ⇒ Object



84
85
86
87
# File 'lib/simple_a2a/models/base.rb', line 84

def ==(other)
  return false unless other.is_a?(self.class)
  self.class.attributes.keys.all? { |n| send(n) == other.send(n) }
end

#to_hObject



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

def to_h
  self.class.attributes.each_with_object({}) do |(name, _), result|
    val = send(name)
    next if val.nil?
    result[camelize(name)] = serialize(val)
  end
end

#to_jsonObject



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

def to_json(*)
  JSON.generate(to_h)
end

#valid?Boolean

Returns:

  • (Boolean)


78
79
80
81
82
# File 'lib/simple_a2a/models/base.rb', line 78

def valid?
  self.class.attributes.all? do |name, opts|
    !opts[:required] || !send(name).nil?
  end
end