class SBF::Client::PhotoEndpoint

Public Instance Methods

create(entity_or_hash, with = {}) click to toggle source
# 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 = {}) click to toggle source
# 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 = {}) click to toggle source
# 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

Private Instance Methods

photo_for_upload(file, data) click to toggle source
# File lib/stbaldricks/endpoints/photo.rb, line 64
        def photo_for_upload(file, data)
  if data.is_a?(SBF::Client::Photo)
    data.file = file
    data
  else
    photo = SBF::Client::Photo.new(data.is_a?(Hash) && data.any? ? data : {})
    photo.file = file
    photo
  end
end