Module: Sinatra::Backstage::StoredFile::Routing

Defined in:
lib/sinatra/backstage/stored_file/stored_file_routes.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(controller) ⇒ Object



6
7
8
# File 'lib/sinatra/backstage/stored_file/stored_file_routes.rb', line 6

def self.included(controller)
  controller.extend self
end

Instance Method Details

#receive_attachment(klass, child_klass, namespace, field_name) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/sinatra/backstage/stored_file/stored_file_routes.rb', line 10

def receive_attachment(klass, child_klass, namespace, field_name)

  helpers Sinatra::Backstage::StoredFile::Helper

  ## Add logo after create franchise
  before "#{namespace}/new", :method => :post do
    if params[:object][field_name]
      begin
        # puts "-- StoredFile before new ( params[:object] = #{params[:object]}"
        attachment = params[:object].delete(field_name)
        attachment_attrs = get_attachment_attrs(attachment)
        # puts "-- StoredFile before new ( attachment_attrs = #{attachment_attrs}"
        params[:object][field_name] = child_klass.create(
          attachment_attrs,
          attachment[:tempfile]
        )
        # puts "-- StoredFile before new ( result params[:object] = #{params[:object]}"
      rescue DataMapper::SaveFailureError => e
        puts e.resource.errors.inspect
      end
    end
  end

  ## Create logo object before update franchise
  before "#{namespace}/:id", :method => :put do |id|
    if params[:object][field_name]
      begin
        attachment = params[:object].delete(field_name)
        attachment_attrs = get_attachment_attrs(attachment)
        child_obj = klass.get!(id).send(field_name)
        if child_obj.nil?
          params[:object][field_name] = child_klass.create(
            attachment_attrs,
            attachment[:tempfile]
          )
        else
          child_obj.update(
            attachment_attrs,
            attachment[:tempfile]
          )
        end
      rescue DataMapper::SaveFailureError => e
        puts e.resource.errors.inspect
      end
    end
  end

  ## Destroy file object
  delete "#{namespace}/:id/#{field_name}" do |id|
    child_obj = klass.get!(id).send(field_name)
    child_obj.destroy unless child_obj.nil?
    redirect "#{namespace}/#{id}"
  end

end