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
18
19
20
# File 'lib/restful_resource/associations.rb', line 3

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

  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?

    nested_resource.map { |obj| klass.new(obj) }
  end
end

#has_one(nested_resource_type) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/restful_resource/associations.rb', line 22

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

  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