Module: ApiResource::Associations::ClassMethods

Defined in:
lib/api_resource/associations.rb

Instance Method Summary collapse

Instance Method Details

#association?(assoc) ⇒ Boolean

Returns:

  • (Boolean)


79
80
81
82
83
84
# File 'lib/api_resource/associations.rb', line 79

def association?(assoc)
  self.related_objects.any? do |key, value|
    next if key.to_s == "scope"
    value.detect { |k,v| k.to_sym == assoc.to_sym }
  end
end

#association_class_name(assoc) ⇒ Object

Raises:

  • (ArgumentError)


86
87
88
89
90
91
92
# File 'lib/api_resource/associations.rb', line 86

def association_class_name(assoc)
  raise ArgumentError, "#{assoc} is not a valid association of #{self}" unless self.association?(assoc)
  result = self.related_objects.detect do |key,value|
    ret = value.detect{|k,v| k.to_sym == assoc.to_sym }
    return ret[1] if ret
  end
end

#clear_associationsObject



94
95
96
97
98
# File 'lib/api_resource/associations.rb', line 94

def clear_associations
  self.related_objects.each do |_, val|
    val.clear
  end
end

#scope(name, hsh) ⇒ Object

Raises:

  • (ArgumentError)


59
60
61
62
63
64
65
66
67
68
# File 'lib/api_resource/associations.rb', line 59

def scope(name, hsh)
  raise ArgumentError, "Expecting an attributes hash given #{hsh.inspect}" unless hsh.is_a?(Hash)
  self.related_objects[:scope][name.to_sym] = hsh
  # we also need to define a class method for each scope
  self.instance_eval <<-EOE, __FILE__, __LINE__ + 1
    def #{name}(opts = {})
      return ApiResource::Associations::ResourceScope.new(self, :#{name}, opts)
    end
  EOE
end

#scope?(name) ⇒ Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/api_resource/associations.rb', line 70

def scope?(name)
  self.related_objects[:scope][name.to_sym].present?
end

#scope_attributes(name) ⇒ Object



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

def scope_attributes(name)
  raise "No such scope #{name}" unless self.scope?(name)
  self.related_objects[:scope][name.to_sym]
end

#scopesObject



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

def scopes
  return self.related_objects[:scope]
end