Module: Flexirest::Associations::ClassMethods

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

Instance Method Summary collapse

Instance Method Details

#_date_fieldsObject



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

def _date_fields
  @_date_fields.uniq
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

#inherited(subclass) ⇒ Object



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

def inherited(subclass)
  subclass.instance_variable_set(:@_date_fields, [])
  super
end

#parse_date(*keys) ⇒ Object



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

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