Module: RestfulResource::Associations

Included in:
Base
Defined in:
lib/restful_resource/associations.rb

Instance Method Summary collapse

Instance Method Details

#has_many(nested_resource_type) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/restful_resource/associations.rb', line 3

def has_many(nested_resource_type)
  namespace = self.to_s.deconstantize
  klass_name = "#{nested_resource_type.to_s.singularize.camelize.to_s}"
  klass_name = "#{namespace}::#{klass_name}" if namespace.present?

  self.send(:define_method, nested_resource_type) do
    klass = begin
      klass_name.safe_constantize
    rescue NameError
      nil
    end
    klass = RestfulResource::OpenObject if (klass.nil? || !(klass < RestfulResource::OpenObject))
    @inner_object.send(nested_resource_type).map { |obj| klass.new(obj) }
  end
end

#has_one(nested_resource_type) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/restful_resource/associations.rb', line 19

def has_one(nested_resource_type)
  namespace = self.to_s.deconstantize
  klass_name = "#{nested_resource_type.to_s.camelize.to_s}"
  klass_name = "#{namespace}::#{klass_name}" if namespace.present?

  self.send(:define_method, nested_resource_type) do
    klass = begin
      klass_name.safe_constantize
    rescue NameError
      nil
    end
    klass = RestfulResource::OpenObject if (klass.nil? || !(klass < RestfulResource::OpenObject))
    nested_resource = @inner_object.send(nested_resource_type)
    return nil if nested_resource.nil?
    klass.new(@inner_object.send(nested_resource_type))
  end
end