Module: GrapeClient::HasMany

Included in:
Base
Defined in:
lib/grape_client/has_many.rb

Instance Method Summary collapse

Instance Method Details

#has_many(property, options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/grape_client/has_many.rb', line 3

def has_many(property, options = {})
  define_method(property) do
    clazz = class_from_name(options[:class_name] || property.to_s.singularize)
    case @attributes[property]
    when Collection then @attributes[property]
    when nil
      @attributes[property] = clazz.where("#{self.class.entity_name}_id" => id)
    else
      @attributes[property].map! do |element|
        next element unless element.is_a? Hash
        clazz.new(element)
      end
    end
  end

  define_method("#{property}=") do |array|
    @attributes[property] = array
  end
end