Class: Ansible::Ruby::Models::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model, ActiveModel::Validations
Defined in:
lib/ansible/ruby/models/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Base

Returns a new instance of Base.



13
14
15
16
# File 'lib/ansible/ruby/models/base.rb', line 13

def initialize(args = {})
  @set_vars = {}
  super
end

Class Method Details

.attr_option(name) ⇒ Object



39
40
41
# File 'lib/ansible/ruby/models/base.rb', line 39

def attr_option(name)
  attr_options[name]
end

.attr_optionsObject



19
20
21
22
23
24
25
# File 'lib/ansible/ruby/models/base.rb', line 19

def attr_options
  @attr_options ||= begin
    # need parent attribute info
    hash = Base > self ? superclass.attr_options : {}
    hash.clone
  end
end

.attribute(name, options = {}) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ansible/ruby/models/base.rb', line 27

def attribute(name, options = {})
  attr_reader name
  # Want to keep track of what we set (avoid default issues)
  ivar = "@#{name}".to_sym
  define_method("#{name}=".to_sym) do |value|
    @set_vars[name] = true
    instance_variable_set ivar, value
  end
  for_name = attr_options[name] ||= {}
  for_name.merge! options
end

.validates(*attributes) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ansible/ruby/models/base.rb', line 43

def validates(*attributes)
  super
  # avoid having to dupe this in the :attribute call
  hash = attributes.length > 1 && attributes[1]
  type_validator = hash && hash[:type]
  return unless type_validator
  if type_validator.is_a?(TypeGeneric)
    name = attributes[0]
    for_name = attr_options[name] ||= {}
    for_name[:generic] = type_validator.klasses
  end
end

Instance Method Details

#to_hObject



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/ansible/ruby/models/base.rb', line 57

def to_h
  validate!
  Hash[
    @set_vars.map do |key, _|
      value = send key
      options = self.class.attr_option(key)
      value = hashify value
      generic_types = options[:generic]
      value = convert_generic generic_types, value if generic_types
      key = options[:original_name] || key
      [key, value]
    end.compact]
end