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



43
44
45
46
47
# File 'lib/ibm_watson/base_model.rb', line 43

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



36
37
38
39
40
# File 'lib/ibm_watson/base_model.rb', line 36

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]

also support Hash attributes

attribute :foo, type: Hash


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ibm_watson/base_model.rb', line 10

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
  elsif type == Hash
    lambda do |value|
      if value.kind_of?(String)
        JSON.parse(value) || {}
      else
        value || {}
      end
    end
  else
    super
  end
end