Class: WixAnswers::Models::Base

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Base

Returns a new instance of Base.



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

def initialize(attrs={})
  self.attrs = attrs.deep_symbolize_keys!

  self.validate!
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(k) ⇒ Object



34
35
36
# File 'lib/wixanswers/models/base.rb', line 34

def method_missing(k)
  self.attrs[k.to_sym]
end

Instance Attribute Details

#attrsObject

Returns the value of attribute attrs.



5
6
7
# File 'lib/wixanswers/models/base.rb', line 5

def attrs
  @attrs
end

Instance Method Details

#validate!Object



13
14
15
16
17
# File 'lib/wixanswers/models/base.rb', line 13

def validate!
  self.validate_schema!

  return self
end

#validate_schema!Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/wixanswers/models/base.rb', line 19

def validate_schema!
  return unless defined?(self.class::SCHEMA)

  # make sure all required params appear and that the supplied arguments match their types
  self.class::SCHEMA.each_pair do |k,v|
    attr = self.attrs[k]

    raise WixAnswers::Exceptions::MissingAttribute.new(k) if v[:required] and attr.nil?

    attr_type = v[:type] == "Boolean" ? ["FalseClass", "TrueClass"] : Array.wrap(v[:type])

    raise WixAnswers::Exceptions::SchemaTypeError.new(v[:type], attr.class.name) if !attr.nil? and !attr_type.include?(attr.class.name)
  end
end