Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Includes:
ToApiFilter
Defined in:
lib/to_api.rb

Instance Method Summary collapse

Methods included from ToApiFilter

#add_to_api_filter, #to_api_filters, #to_api_filters=

Instance Method Details

#to_api(*includes) ⇒ Object

assumes all attribute types are fine



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/to_api.rb', line 59

def to_api(*includes) #assumes all attribute types are fine
  hash = {}
  valid_includes = (self.class.reflect_on_all_associations.map(&:name).map(&:to_s) | self.valid_api_includes | self.attributes.keys)

  include_hash = build_to_api_ar_include_hash(*includes)
  include_hash.keys.each do |inc|
    if to_api_filters.has_key?(inc)
      child_includes = include_hash.delete(inc) || []
      hash[inc] = to_api_filters[inc].call self, child_includes
    end
  end

  include_hash.delete_if{|k,v| !valid_includes.include?(k.to_s)}
  to_api_attributes.each do |k, v|
    unless hash[k]
      v.to_api_filters = to_api_filters if to_api_filters.any? && v.respond_to?(:to_api_filters)

      attribute_includes = include_hash[k] || []
      to_api_v = v.to_api(*[attribute_includes].flatten.compact)
      hash[k] = to_api_v
    end
  end

  (include_hash.keys-to_api_attributes.keys).each do |relation|
    unless hash[relation]
      relation_includes = include_hash[relation] || []
      api_obj = self.send(relation)
      api_obj.to_api_filters = to_api_filters if api_obj.respond_to?(:to_api_filters)

      hash[relation.to_s] = api_obj.respond_to?(:to_api) ? api_obj.to_api(*[relation_includes].flatten.compact) : api_obj
    end
  end

  hash
end

#to_api_attributesObject



100
101
102
# File 'lib/to_api.rb', line 100

def to_api_attributes
  attributes
end

#valid_api_includesObject

override in models



96
97
98
# File 'lib/to_api.rb', line 96

def valid_api_includes
  []
end