Class: SBF::Client::PhotoEndpoint

Inherits:
EntityEndpoint show all
Defined in:
lib/stbaldricks/endpoints/photo.rb

Instance Attribute Summary

Attributes inherited from EntityEndpoint

#orig_target_class

Instance Method Summary collapse

Methods inherited from EntityEndpoint

#aggregate, #delete, #find, #find_first, #get, #initialize, #save

Constructor Details

This class inherits a constructor from SBF::Client::EntityEndpoint

Instance Method Details

#create(entity_or_hash, with = {}) ⇒ Object

Raises:



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/stbaldricks/endpoints/photo.rb', line 6

def create(entity_or_hash, with = {})
  entity = entity_or_hash.is_a?(Hash) ? target_class.new(entity_or_hash) : entity_or_hash
  raise SBF::Client::Error, 'Invalid Entity' unless entity.is_a?(SBF::Client::BaseEntity)

  with = normalize_with(with)

  create_data = entity.dirty_data
  filename = create_data.delete(:filename)
  file = create_data.delete(:file)
  create_data.store(:with, with)

  response = SBF::Client::Api::Request.file_post_request(path: "#{base_uri}/create", params: create_data, file: file, filename: filename)

  hydrated_entity(response, create_data, entity)
end

#update(id = nil, entity_or_hash = nil, with = {}) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/stbaldricks/endpoints/photo.rb', line 22

def update(id = nil, entity_or_hash = nil, with = {})
  if entity_or_hash.is_a?(SBF::Client::BaseEntity)
    # If someone has passed in an entity, just convert it to a hash
    data = entity_or_hash.dirty_data
    data[:id] = id unless id.nil?
    data[:id] = entity_or_hash.id if id.nil? && !entity_or_hash.id.nil?
  elsif entity_or_hash.is_a?(Hash)
    # If someone has passed in a hash, make sure all of it's values match fields in the entity class
    data = sanitize(entity_or_hash)
  else
    raise SBF::Client::Error, 'Invalid Data'
  end

  filename = data.delete(:filename)
  file = data.delete(:file)

  with = normalize_with(with)
  data[:with] = with
  response = if file
               SBF::Client::Api::Request.file_post_request(path: "#{base_uri}/update", params: data, file: file, filename: filename)
             else
               SBF::Client::Api::Request.post_request("#{base_uri}/update", data)
             end

  hydrated_entity(response, data, entity_or_hash)
end

#upload(image_data_url, data = {}, with = {}) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/stbaldricks/endpoints/photo.rb', line 49

def upload(image_data_url, data = {}, with = {})
  # support image formats: png, jpeg, gif
  image_data_url.slice!(%r{data:image/(png|jpeg|gif);base64,})
  image_data = Base64.decode64(image_data_url)

  Tempfile.create('photo_upload') do |file|
    file.binmode
    file.write(image_data)
    file.seek(0)

    photo = photo_for_upload(file, data)
    photo.id.nil? ? create(photo, with) : update(photo.id, photo, with)
  end
end