Module: Her::Model::ORM::FindMethods::ClassMethods

Defined in:
lib/her/model/orm/find_methods.rb

Instance Method Summary collapse

Instance Method Details

#find(*ids) ⇒ Object

Fetch specific resource(s) by their ID

Examples:

@user = User.find(1)
# Fetched via GET "/users/1"
@users = User.find([1, 2])
# Fetched via GET "/users/1" and GET "/users/2"


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/her/model/orm/find_methods.rb', line 17

def find(*ids)
  params = ids.last.is_a?(Hash) ? ids.pop : {}
  prepared_ids = ids.flatten.compact.uniq
  results = prepared_ids.map do |id|
    resource = nil
    request(params.merge(_method: :get, _path: build_request_path(params.merge(id: id)))) do |parsed_data|
      resource = new(parse(parsed_data[:data]).merge _metadata: parsed_data[:data], _errors: parsed_data[:errors])
      wrap_in_hooks(resource, :find)
    end
    resource
  end
  if ids.length > 1 || ids.first.kind_of?(Array)
    raise RecordNotFound.one(self.class, ids) if results.nil?
    results
  else
    raise RecordNotFound.some(self.class, ids, results.length, prepared_ids.length) if results.length != prepared_ids.length
    results.first
  end
end

#find_by_id(id) ⇒ Object



37
38
39
40
41
# File 'lib/her/model/orm/find_methods.rb', line 37

def find_by_id(id)
  find(id)
rescue RecordNotFound
  nil
end