Module: Flexirest::Associations::ClassMethods

Includes:
ActiveSupport::Inflector
Defined in:
lib/flexirest/associations.rb

Instance Method Summary collapse

Instance Method Details

#_associationsObject



75
76
77
# File 'lib/flexirest/associations.rb', line 75

def _associations
  @_associations
end

#_date_fieldsObject



71
72
73
# File 'lib/flexirest/associations.rb', line 71

def _date_fields
  @_date_fields.uniq
end

#_include_associationsObject



59
60
61
# File 'lib/flexirest/associations.rb', line 59

def _include_associations
  @_include_associations
end

#_reset_include_associations!Object



63
64
65
# File 'lib/flexirest/associations.rb', line 63

def _reset_include_associations!
  @_include_associations = []
end

#has_many(key, klass = nil) ⇒ Object



6
7
8
9
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/flexirest/associations.rb', line 6

def has_many(key, klass = nil)
  if klass.nil?
    klass = key.to_s.classify.constantize
  end

  @_associations ||= {}
  @_associations[key] = klass
  define_method(key) do
    unless _attributes[key].is_a?(Array) || _attributes[key].is_a?(Flexirest::ResultIterator)
      return _attributes[key]
    end

    if _attributes[key].size == 0
      return _attributes[key]
    end

    if _attributes[key][0].is_a?(klass)
      return _attributes[key]
    end

    _attributes[key].each_with_index do |v, k|
      _attributes[key][k] = klass.new(v)
    end

    _attributes[key]
  end
end

#has_one(key, klass = nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/flexirest/associations.rb', line 34

def has_one(key, klass = nil)
  if klass.nil?
    klass = key.to_s.classify.constantize
  end

  @_associations ||= {}
  @_associations[key] = klass
  define_method(key) do
    return nil if _attributes[key].nil?

    if _attributes[key].is_a?(klass)
      return _attributes[key]
    end

    _attributes[key] = klass.new(_attributes[key])

    _attributes[key]
  end
end

#includes(*keys) ⇒ Object



54
55
56
57
# File 'lib/flexirest/associations.rb', line 54

def includes(*keys)
  @_include_associations = keys
  self
end

#inherited(subclass) ⇒ Object



80
81
82
83
84
85
# File 'lib/flexirest/associations.rb', line 80

def inherited(subclass)
  subclass.instance_variable_set(:@_date_fields, [])
  subclass.instance_variable_set(:@_associations, {})
  subclass.instance_variable_set(:@_include_associations, [])
  super
end

#parse_date(*keys) ⇒ Object



67
68
69
# File 'lib/flexirest/associations.rb', line 67

def parse_date(*keys)
  keys.each { |key| @_date_fields << key }
end