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



51
52
53
# File 'lib/ansible/ruby/models/base.rb', line 51

def attr_option(name)
  attr_options[name]
end

.attr_optionsObject



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

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

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



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ansible/ruby/models/base.rb', line 39

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

.remove_existing_validations(attr) ⇒ Object



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

def remove_existing_validations(attr)
  options = attr_option(attr)
  options.clear
  _validators.delete attr
  callbacks = send(:get_callbacks, :validate)
  for_this_att = callbacks.select do |callback|
    filter = callback.filter
    filter.respond_to?(:attributes) && filter.attributes == [attr]
  end
  for_this_att.each { |callback| callbacks.delete callback }
end

.validates(*attributes) ⇒ Object



55
56
57
58
59
60
61
62
63
64
# File 'lib/ansible/ruby/models/base.rb', line 55

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 && type_validator.is_a?(TypeGeneric)
  name = attributes[0]
  for_name = attr_options[name] ||= {}
  for_name[:generic] = type_validator.klasses
end

Instance Method Details

#to_hObject



67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/ansible/ruby/models/base.rb', line 67

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