Class: IBMWatson::BaseModel

Inherits:
Object
  • Object
show all
Includes:
ActiveAttr::AttributeDefaults, ActiveAttr::Model
Defined in:
lib/ibm_watson/base_model.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.collection_attribute_namesObject

All [BaseModel] typed attributes are considered here



33
34
35
36
37
# File 'lib/ibm_watson/base_model.rb', line 33

def self.collection_attribute_names
  attributes.select { |name, attribute|
    attribute[:type].present? && attribute[:type].is_a?(Array) && attribute[:type].first <= BaseModel
  }.map { |name, attribute| name }
end

Instance Method Details

#as_json(options = nil) ⇒ Object

By default add all collection attributes are considered as if they were associations this will make sure that as_json is called on them properly



26
27
28
29
30
# File 'lib/ibm_watson/base_model.rb', line 26

def as_json(options = nil)
  options ||= {}
  options[:include] = self.class.collection_attribute_names
  super(options)
end

#typecaster_for(type) ⇒ Object

Support “Collection” attributes, eg:

attribute :foo, type: [String]


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/ibm_watson/base_model.rb', line 8

def typecaster_for(type)
  if type.kind_of?(Array) && type.length == 1 && type.first.is_a?(Class)
    item_type = type.first
    lambda do |value|
      value.map { |item|
        unless item.is_a?(item_type)
          item = item_type.new(item)
        end
        item
      }
    end
  else
    super
  end
end