Browse files

init commit

  • Loading branch information...
0 parents commit c4330342de015c98ec708af9fee6cb9179ed223a @yortz committed Oct 21, 2011
Showing with 3,014 additions and 0 deletions.
  1. +5 −0 .gitignore
  2. +13 −0 Gemfile
  3. +120 −0 Gemfile.lock
  4. +261 −0 README
  5. +7 −0 Rakefile
  6. BIN app/assets/images/pbar-ani.gif
  7. +9 −0 app/assets/javascripts/application.js
  8. +652 −0 app/assets/javascripts/jquery.fileupload-ui.js
  9. +760 −0 app/assets/javascripts/jquery.fileupload.js
  10. +156 −0 app/assets/javascripts/jquery.iframe-transport.js
  11. +3 −0 app/assets/javascripts/pictures.js.coffee
  12. +7 −0 app/assets/stylesheets/application.css
  13. +100 −0 app/assets/stylesheets/jquery.fileupload-ui.css
  14. +3 −0 app/assets/stylesheets/pictures.css.scss
  15. +56 −0 app/assets/stylesheets/scaffolds.css.scss
  16. +3 −0 app/controllers/application_controller.rb
  17. +83 −0 app/controllers/pictures_controller.rb
  18. +2 −0 app/helpers/application_helper.rb
  19. +23 −0 app/helpers/error_messages_helper.rb
  20. +22 −0 app/helpers/layout_helper.rb
  21. +2 −0 app/helpers/pictures_helper.rb
  22. 0 app/mailers/.gitkeep
  23. 0 app/models/.gitkeep
  24. +4 −0 app/models/picture.rb
  25. +52 −0 app/uploaders/image_uploader.rb
  26. +19 −0 app/views/layouts/application.html.erb
  27. +29 −0 app/views/pictures/_form.html.erb
  28. +6 −0 app/views/pictures/edit.html.erb
  29. +27 −0 app/views/pictures/index.html.erb
  30. +5 −0 app/views/pictures/new.html.erb
  31. +20 −0 app/views/pictures/show.html.erb
  32. +4 −0 config.ru
  33. +54 −0 config/application.rb
  34. +6 −0 config/boot.rb
  35. +42 −0 config/database.yml
  36. +5 −0 config/environment.rb
  37. +30 −0 config/environments/development.rb
  38. +60 −0 config/environments/production.rb
  39. +39 −0 config/environments/test.rb
  40. +7 −0 config/initializers/backtrace_silencers.rb
  41. +10 −0 config/initializers/inflections.rb
  42. +5 −0 config/initializers/mime_types.rb
  43. +7 −0 config/initializers/secret_token.rb
  44. +8 −0 config/initializers/session_store.rb
  45. +14 −0 config/initializers/wrap_parameters.rb
  46. +5 −0 config/locales/en.yml
  47. +61 −0 config/routes.rb
  48. +11 −0 db/migrate/20111021151343_create_pictures.rb
  49. +24 −0 db/schema.rb
  50. +7 −0 db/seeds.rb
  51. +2 −0 doc/README_FOR_APP
  52. 0 lib/assets/.gitkeep
  53. 0 lib/tasks/.gitkeep
  54. 0 log/.gitkeep
  55. +26 −0 public/404.html
  56. +26 −0 public/422.html
  57. +26 −0 public/500.html
  58. 0 public/favicon.ico
  59. +5 −0 public/robots.txt
  60. +75 −0 public/stylesheets/application.css
  61. +6 −0 script/rails
  62. 0 vendor/assets/stylesheets/.gitkeep
  63. 0 vendor/plugins/.gitkeep
5 .gitignore
@@ -0,0 +1,5 @@
+.bundle
+db/*.sqlite3
+log/*.log
+tmp/
+.sass-cache/
13 Gemfile
@@ -0,0 +1,13 @@
+source 'http://rubygems.org'
+
+gem 'rails', '3.1.1'
+gem 'mysql2'
+gem 'jquery-rails'
+gem 'nifty-generators'
+gem 'carrierwave'
+
+group :assets do
+ gem 'sass-rails', '~> 3.1.4'
+ gem 'coffee-rails', '~> 3.1.1'
+ gem 'uglifier', '>= 1.0.3'
+end
120 Gemfile.lock
@@ -0,0 +1,120 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ actionmailer (3.1.1)
+ actionpack (= 3.1.1)
+ mail (~> 2.3.0)
+ actionpack (3.1.1)
+ activemodel (= 3.1.1)
+ activesupport (= 3.1.1)
+ builder (~> 3.0.0)
+ erubis (~> 2.7.0)
+ i18n (~> 0.6)
+ rack (~> 1.3.2)
+ rack-cache (~> 1.1)
+ rack-mount (~> 0.8.2)
+ rack-test (~> 0.6.1)
+ sprockets (~> 2.0.2)
+ activemodel (3.1.1)
+ activesupport (= 3.1.1)
+ builder (~> 3.0.0)
+ i18n (~> 0.6)
+ activerecord (3.1.1)
+ activemodel (= 3.1.1)
+ activesupport (= 3.1.1)
+ arel (~> 2.2.1)
+ tzinfo (~> 0.3.29)
+ activeresource (3.1.1)
+ activemodel (= 3.1.1)
+ activesupport (= 3.1.1)
+ activesupport (3.1.1)
+ multi_json (~> 1.0)
+ arel (2.2.1)
+ builder (3.0.0)
+ carrierwave (0.5.7)
+ activesupport (~> 3.0)
+ coffee-rails (3.1.1)
+ coffee-script (>= 2.2.0)
+ railties (~> 3.1.0)
+ coffee-script (2.2.0)
+ coffee-script-source
+ execjs
+ coffee-script-source (1.1.2)
+ erubis (2.7.0)
+ execjs (1.2.9)
+ multi_json (~> 1.0)
+ hike (1.2.1)
+ i18n (0.6.0)
+ jquery-rails (1.0.16)
+ railties (~> 3.0)
+ thor (~> 0.14)
+ json (1.6.1)
+ mail (2.3.0)
+ i18n (>= 0.4.0)
+ mime-types (~> 1.16)
+ treetop (~> 1.4.8)
+ mime-types (1.16)
+ multi_json (1.0.3)
+ mysql2 (0.3.7)
+ nifty-generators (0.4.6)
+ polyglot (0.3.2)
+ rack (1.3.5)
+ rack-cache (1.1)
+ rack (>= 0.4)
+ rack-mount (0.8.3)
+ rack (>= 1.0.0)
+ rack-ssl (1.3.2)
+ rack
+ rack-test (0.6.1)
+ rack (>= 1.0)
+ rails (3.1.1)
+ actionmailer (= 3.1.1)
+ actionpack (= 3.1.1)
+ activerecord (= 3.1.1)
+ activeresource (= 3.1.1)
+ activesupport (= 3.1.1)
+ bundler (~> 1.0)
+ railties (= 3.1.1)
+ railties (3.1.1)
+ actionpack (= 3.1.1)
+ activesupport (= 3.1.1)
+ rack-ssl (~> 1.3.2)
+ rake (>= 0.8.7)
+ rdoc (~> 3.4)
+ thor (~> 0.14.6)
+ rake (0.9.2)
+ rdoc (3.11)
+ json (~> 1.4)
+ sass (3.1.10)
+ sass-rails (3.1.4)
+ actionpack (~> 3.1.0)
+ railties (~> 3.1.0)
+ sass (>= 3.1.4)
+ sprockets (~> 2.0.0)
+ tilt (~> 1.3.2)
+ sprockets (2.0.3)
+ hike (~> 1.2)
+ rack (~> 1.0)
+ tilt (~> 1.1, != 1.3.0)
+ thor (0.14.6)
+ tilt (1.3.3)
+ treetop (1.4.10)
+ polyglot
+ polyglot (>= 0.3.1)
+ tzinfo (0.3.30)
+ uglifier (1.0.4)
+ execjs (>= 0.3.0)
+ multi_json (>= 1.0.2)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ carrierwave
+ coffee-rails (~> 3.1.1)
+ jquery-rails
+ mysql2
+ nifty-generators
+ rails (= 3.1.1)
+ sass-rails (~> 3.1.4)
+ uglifier (>= 1.0.3)
261 README
@@ -0,0 +1,261 @@
+== Welcome to Rails
+
+Rails is a web-application framework that includes everything needed to create
+database-backed web applications according to the Model-View-Control pattern.
+
+This pattern splits the view (also called the presentation) into "dumb"
+templates that are primarily responsible for inserting pre-built data in between
+HTML tags. The model contains the "smart" domain objects (such as Account,
+Product, Person, Post) that holds all the business logic and knows how to
+persist themselves to a database. The controller handles the incoming requests
+(such as Save New Account, Update Product, Show Post) by manipulating the model
+and directing data to the view.
+
+In Rails, the model is handled by what's called an object-relational mapping
+layer entitled Active Record. This layer allows you to present the data from
+database rows as objects and embellish these data objects with business logic
+methods. You can read more about Active Record in
+link:files/vendor/rails/activerecord/README.html.
+
+The controller and view are handled by the Action Pack, which handles both
+layers by its two parts: Action View and Action Controller. These two layers
+are bundled in a single package due to their heavy interdependence. This is
+unlike the relationship between the Active Record and Action Pack that is much
+more separate. Each of these packages can be used independently outside of
+Rails. You can read more about Action Pack in
+link:files/vendor/rails/actionpack/README.html.
+
+
+== Getting Started
+
+1. At the command prompt, create a new Rails application:
+ <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
+
+2. Change directory to <tt>myapp</tt> and start the web server:
+ <tt>cd myapp; rails server</tt> (run with --help for options)
+
+3. Go to http://localhost:3000/ and you'll see:
+ "Welcome aboard: You're riding Ruby on Rails!"
+
+4. Follow the guidelines to start developing your application. You can find
+the following resources handy:
+
+* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
+* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
+
+
+== Debugging Rails
+
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
+will help you debug it and get it back on the rails.
+
+First area to check is the application log files. Have "tail -f" commands
+running on the server.log and development.log. Rails will automatically display
+debugging and runtime information to these files. Debugging info will also be
+shown in the browser on requests from 127.0.0.1.
+
+You can also log your own messages directly into the log file from your code
+using the Ruby logger class from inside your controllers. Example:
+
+ class WeblogController < ActionController::Base
+ def destroy
+ @weblog = Weblog.find(params[:id])
+ @weblog.destroy
+ logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
+ end
+ end
+
+The result will be a message in your log file along the lines of:
+
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
+
+More information on how to use the logger is at http://www.ruby-doc.org/core/
+
+Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
+several books available online as well:
+
+* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+
+These two books will bring you up to speed on the Ruby language and also on
+programming in general.
+
+
+== Debugger
+
+Debugger support is available through the debugger command when you start your
+Mongrel or WEBrick server with --debugger. This means that you can break out of
+execution at any point in the code, investigate and change the model, and then,
+resume execution! You need to install ruby-debug to run the server in debugging
+mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.all
+ debugger
+ end
+ end
+
+So the controller will accept the action, run the first line, then present you
+with a IRB prompt in the server window. Here you can do things like:
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8
+ @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
+ #<Post:0x14a6620
+ @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
+ >> @posts.first.title = "hello from a debugger"
+ => "hello from a debugger"
+
+...and even better, you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+Finally, when you're ready to resume execution, you can enter "cont".
+
+
+== Console
+
+The console is a Ruby shell, which allows you to interact with your
+application's domain model. Here you'll have all parts of the application
+configured, just like it is when the application is running. You can inspect
+domain models, change values, and save to the database. Starting the script
+without arguments will launch it in the development environment.
+
+To start the console, run <tt>rails console</tt> from the application
+directory.
+
+Options:
+
+* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
+ made to the database.
+* Passing an environment name as an argument will load the corresponding
+ environment. Example: <tt>rails console production</tt>.
+
+To reload your controllers and models after launching the console run
+<tt>reload!</tt>
+
+More information about irb can be found at:
+link:http://www.rubycentral.org/pickaxe/irb.html
+
+
+== dbconsole
+
+You can go to the command line of your database directly through <tt>rails
+dbconsole</tt>. You would be connected to the database with the credentials
+defined in database.yml. Starting the script without arguments will connect you
+to the development database. Passing an argument will connect you to a different
+database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
+PostgreSQL and SQLite 3.
+
+== Description of Contents
+
+The default directory structure of a generated Ruby on Rails application:
+
+ |-- app
+ | |-- assets
+ | |-- images
+ | |-- javascripts
+ | `-- stylesheets
+ | |-- controllers
+ | |-- helpers
+ | |-- mailers
+ | |-- models
+ | `-- views
+ | `-- layouts
+ |-- config
+ | |-- environments
+ | |-- initializers
+ | `-- locales
+ |-- db
+ |-- doc
+ |-- lib
+ | `-- tasks
+ |-- log
+ |-- public
+ |-- script
+ |-- test
+ | |-- fixtures
+ | |-- functional
+ | |-- integration
+ | |-- performance
+ | `-- unit
+ |-- tmp
+ | |-- cache
+ | |-- pids
+ | |-- sessions
+ | `-- sockets
+ `-- vendor
+ |-- assets
+ `-- stylesheets
+ `-- plugins
+
+app
+ Holds all the code that's specific to this particular application.
+
+app/assets
+ Contains subdirectories for images, stylesheets, and JavaScript files.
+
+app/controllers
+ Holds controllers that should be named like weblogs_controller.rb for
+ automated URL mapping. All controllers should descend from
+ ApplicationController which itself descends from ActionController::Base.
+
+app/models
+ Holds models that should be named like post.rb. Models descend from
+ ActiveRecord::Base by default.
+
+app/views
+ Holds the template files for the view that should be named like
+ weblogs/index.html.erb for the WeblogsController#index action. All views use
+ eRuby syntax by default.
+
+app/views/layouts
+ Holds the template files for layouts to be used with views. This models the
+ common header/footer method of wrapping views. In your views, define a layout
+ using the <tt>layout :default</tt> and create a file named default.html.erb.
+ Inside default.html.erb, call <% yield %> to render the view using this
+ layout.
+
+app/helpers
+ Holds view helpers that should be named like weblogs_helper.rb. These are
+ generated for you automatically when using generators for controllers.
+ Helpers can be used to wrap functionality for your views into methods.
+
+config
+ Configuration files for the Rails environment, the routing map, the database,
+ and other dependencies.
+
+db
+ Contains the database schema in schema.rb. db/migrate contains all the
+ sequence of Migrations for your schema.
+
+doc
+ This directory is where your application documentation will be stored when
+ generated using <tt>rake doc:app</tt>
+
+lib
+ Application specific libraries. Basically, any kind of custom code that
+ doesn't belong under controllers, models, or helpers. This directory is in
+ the load path.
+
+public
+ The directory available for the web server. Also contains the dispatchers and the
+ default HTML files. This should be set as the DOCUMENT_ROOT of your web
+ server.
+
+script
+ Helper scripts for automation and generation.
+
+test
+ Unit and functional tests along with fixtures. When using the rails generate
+ command, template test files will be generated for you and placed in this
+ directory.
+
+vendor
+ External libraries that the application depends on. Also includes the plugins
+ subdirectory. If the app has frozen rails, those gems also go here, under
+ vendor/rails/. This directory is in the load path.
7 Rakefile
@@ -0,0 +1,7 @@
+#!/usr/bin/env rake
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+
+CarrierwaveJqueryFileUpload::Application.load_tasks
BIN app/assets/images/pbar-ani.gif
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 app/assets/javascripts/application.js
@@ -0,0 +1,9 @@
+// This is a manifest file that'll be compiled into including all the files listed below.
+// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
+// be included in the compiled file accessible from http://example.com/assets/application.js
+// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
+// the compiled file.
+//
+//= require jquery
+//= require jquery_ujs
+//= require_tree .
652 app/assets/javascripts/jquery.fileupload-ui.js
@@ -0,0 +1,652 @@
+/*
+ * jQuery File Upload User Interface Plugin 5.0.17
+ * https://github.com/blueimp/jQuery-File-Upload
+ *
+ * Copyright 2010, Sebastian Tschan
+ * https://blueimp.net
+ *
+ * Licensed under the MIT license:
+ * http://creativecommons.org/licenses/MIT/
+ */
+
+/*jslint nomen: true, unparam: true, regexp: true */
+/*global window, document, URL, webkitURL, FileReader, jQuery */
+
+(function ($) {
+ 'use strict';
+
+ // The UI version extends the basic fileupload widget and adds
+ // a complete user interface based on the given upload/download
+ // templates.
+ $.widget('blueimpUI.fileupload', $.blueimp.fileupload, {
+
+ options: {
+ // By default, files added to the widget are uploaded as soon
+ // as the user clicks on the start buttons. To enable automatic
+ // uploads, set the following option to true:
+ autoUpload: false,
+ // The following option limits the number of files that are
+ // allowed to be uploaded using this widget:
+ maxNumberOfFiles: undefined,
+ // The maximum allowed file size:
+ maxFileSize: undefined,
+ // The minimum allowed file size:
+ minFileSize: 1,
+ // The regular expression for allowed file types, matches
+ // against either file type or file name:
+ acceptFileTypes: /.+$/i,
+ // The regular expression to define for which files a preview
+ // image is shown, matched against the file type:
+ previewFileTypes: /^image\/(gif|jpeg|png)$/,
+ // The maximum width of the preview images:
+ previewMaxWidth: 80,
+ // The maximum height of the preview images:
+ previewMaxHeight: 80,
+ // By default, preview images are displayed as canvas elements
+ // if supported by the browser. Set the following option to false
+ // to always display preview images as img elements:
+ previewAsCanvas: true,
+ // The file upload template that is given as first argument to the
+ // jQuery.tmpl method to render the file uploads:
+ uploadTemplate: $('#template-upload'),
+ // The file download template, that is given as first argument to the
+ // jQuery.tmpl method to render the file downloads:
+ downloadTemplate: $('#template-download'),
+ // The expected data type of the upload response, sets the dataType
+ // option of the $.ajax upload requests:
+ dataType: 'json',
+
+ // The add callback is invoked as soon as files are added to the fileupload
+ // widget (via file input selection, drag & drop or add API call).
+ // See the basic file upload widget for more information:
+ add: function (e, data) {
+ var that = $(this).data('fileupload');
+ that._adjustMaxNumberOfFiles(-data.files.length);
+ data.isAdjusted = true;
+ data.isValidated = that._validate(data.files);
+ data.context = that._renderUpload(data.files)
+ .appendTo($(this).find('.files')).fadeIn(function () {
+ // Fix for IE7 and lower:
+ $(this).show();
+ }).data('data', data);
+ if ((that.options.autoUpload || data.autoUpload) &&
+ data.isValidated) {
+ data.jqXHR = data.submit();
+ }
+ },
+ // Callback for the start of each file upload request:
+ send: function (e, data) {
+ if (!data.isValidated) {
+ var that = $(this).data('fileupload');
+ if (!data.isAdjusted) {
+ that._adjustMaxNumberOfFiles(-data.files.length);
+ }
+ if (!that._validate(data.files)) {
+ return false;
+ }
+ }
+ if (data.context && data.dataType &&
+ data.dataType.substr(0, 6) === 'iframe') {
+ // Iframe Transport does not support progress events.
+ // In lack of an indeterminate progress bar, we set
+ // the progress to 100%, showing the full animated bar:
+ data.context.find('.ui-progressbar').progressbar(
+ 'value',
+ parseInt(100, 10)
+ );
+ }
+ },
+ // Callback for successful uploads:
+ done: function (e, data) {
+ var that = $(this).data('fileupload');
+ if (data.context) {
+ data.context.each(function (index) {
+ var file = ($.isArray(data.result) &&
+ data.result[index]) || {error: 'emptyResult'};
+ if (file.error) {
+ that._adjustMaxNumberOfFiles(1);
+ }
+ $(this).fadeOut(function () {
+ that._renderDownload([file])
+ .css('display', 'none')
+ .replaceAll(this)
+ .fadeIn(function () {
+ // Fix for IE7 and lower:
+ $(this).show();
+ });
+ });
+ });
+ } else {
+ that._renderDownload(data.result)
+ .css('display', 'none')
+ .appendTo($(this).find('.files'))
+ .fadeIn(function () {
+ // Fix for IE7 and lower:
+ $(this).show();
+ });
+ }
+ },
+ // Callback for failed (abort or error) uploads:
+ fail: function (e, data) {
+ var that = $(this).data('fileupload');
+ that._adjustMaxNumberOfFiles(data.files.length);
+ if (data.context) {
+ data.context.each(function (index) {
+ $(this).fadeOut(function () {
+ if (data.errorThrown !== 'abort') {
+ var file = data.files[index];
+ file.error = file.error || data.errorThrown
+ || true;
+ that._renderDownload([file])
+ .css('display', 'none')
+ .replaceAll(this)
+ .fadeIn(function () {
+ // Fix for IE7 and lower:
+ $(this).show();
+ });
+ } else {
+ data.context.remove();
+ }
+ });
+ });
+ } else if (data.errorThrown !== 'abort') {
+ that._adjustMaxNumberOfFiles(-data.files.length);
+ data.context = that._renderUpload(data.files)
+ .css('display', 'none')
+ .appendTo($(this).find('.files'))
+ .fadeIn(function () {
+ // Fix for IE7 and lower:
+ $(this).show();
+ }).data('data', data);
+ }
+ },
+ // Callback for upload progress events:
+ progress: function (e, data) {
+ if (data.context) {
+ data.context.find('.ui-progressbar').progressbar(
+ 'value',
+ parseInt(data.loaded / data.total * 100, 10)
+ );
+ }
+ },
+ // Callback for global upload progress events:
+ progressall: function (e, data) {
+ $(this).find('.fileupload-progressbar').progressbar(
+ 'value',
+ parseInt(data.loaded / data.total * 100, 10)
+ );
+ },
+ // Callback for uploads start, equivalent to the global ajaxStart event:
+ start: function () {
+ $(this).find('.fileupload-progressbar')
+ .progressbar('value', 0).fadeIn();
+ },
+ // Callback for uploads stop, equivalent to the global ajaxStop event:
+ stop: function () {
+ $(this).find('.fileupload-progressbar').fadeOut();
+ },
+ // Callback for file deletion:
+ destroy: function (e, data) {
+ var that = $(this).data('fileupload');
+ if (data.url) {
+ $.ajax(data)
+ .success(function () {
+ that._adjustMaxNumberOfFiles(1);
+ $(this).fadeOut(function () {
+ $(this).remove();
+ });
+ });
+ } else {
+ that._adjustMaxNumberOfFiles(1);
+ data.context.fadeOut(function () {
+ $(this).remove();
+ });
+ }
+ }
+ },
+
+ // Scales the given image (img HTML element)
+ // using the given options.
+ // Returns a canvas object if the canvas option is true
+ // and the browser supports canvas, else the scaled image:
+ _scaleImage: function (img, options) {
+ options = options || {};
+ var canvas = document.createElement('canvas'),
+ scale = Math.min(
+ (options.maxWidth || img.width) / img.width,
+ (options.maxHeight || img.height) / img.height
+ );
+ if (scale >= 1) {
+ scale = Math.max(
+ (options.minWidth || img.width) / img.width,
+ (options.minHeight || img.height) / img.height
+ );
+ }
+ img.width = parseInt(img.width * scale, 10);
+ img.height = parseInt(img.height * scale, 10);
+ if (!options.canvas || !canvas.getContext) {
+ return img;
+ }
+ canvas.width = img.width;
+ canvas.height = img.height;
+ canvas.getContext('2d')
+ .drawImage(img, 0, 0, img.width, img.height);
+ return canvas;
+ },
+
+ _createObjectURL: function (file) {
+ var undef = 'undefined',
+ urlAPI = (typeof window.createObjectURL !== undef && window) ||
+ (typeof URL !== undef && URL) ||
+ (typeof webkitURL !== undef && webkitURL);
+ return urlAPI ? urlAPI.createObjectURL(file) : false;
+ },
+
+ _revokeObjectURL: function (url) {
+ var undef = 'undefined',
+ urlAPI = (typeof window.revokeObjectURL !== undef && window) ||
+ (typeof URL !== undef && URL) ||
+ (typeof webkitURL !== undef && webkitURL);
+ return urlAPI ? urlAPI.revokeObjectURL(url) : false;
+ },
+
+ // Loads a given File object via FileReader interface,
+ // invokes the callback with a data url:
+ _loadFile: function (file, callback) {
+ if (typeof FileReader !== 'undefined' &&
+ FileReader.prototype.readAsDataURL) {
+ var fileReader = new FileReader();
+ fileReader.onload = function (e) {
+ callback(e.target.result);
+ };
+ fileReader.readAsDataURL(file);
+ return true;
+ }
+ return false;
+ },
+
+ // Loads an image for a given File object.
+ // Invokes the callback with an img or optional canvas
+ // element (if supported by the browser) as parameter:
+ _loadImage: function (file, callback, options) {
+ var that = this,
+ url,
+ img;
+ if (!options || !options.fileTypes ||
+ options.fileTypes.test(file.type)) {
+ url = this._createObjectURL(file);
+ img = $('<img>').bind('load', function () {
+ $(this).unbind('load');
+ that._revokeObjectURL(url);
+ callback(that._scaleImage(img[0], options));
+ });
+ if (url) {
+ img.prop('src', url);
+ return true;
+ } else {
+ return this._loadFile(file, function (url) {
+ img.prop('src', url);
+ });
+ }
+ }
+ return false;
+ },
+
+ // Link handler, that allows to download files
+ // by drag & drop of the links to the desktop:
+ _enableDragToDesktop: function () {
+ var link = $(this),
+ url = link.prop('href'),
+ name = decodeURIComponent(url.split('/').pop())
+ .replace(/:/g, '-'),
+ type = 'application/octet-stream';
+ link.bind('dragstart', function (e) {
+ try {
+ e.originalEvent.dataTransfer.setData(
+ 'DownloadURL',
+ [type, name, url].join(':')
+ );
+ } catch (err) {}
+ });
+ },
+
+ _adjustMaxNumberOfFiles: function (operand) {
+ if (typeof this.options.maxNumberOfFiles === 'number') {
+ this.options.maxNumberOfFiles += operand;
+ if (this.options.maxNumberOfFiles < 1) {
+ this._disableFileInputButton();
+ } else {
+ this._enableFileInputButton();
+ }
+ }
+ },
+
+ _formatFileSize: function (file) {
+ if (typeof file.size !== 'number') {
+ return '';
+ }
+ if (file.size >= 1000000000) {
+ return (file.size / 1000000000).toFixed(2) + ' GB';
+ }
+ if (file.size >= 1000000) {
+ return (file.size / 1000000).toFixed(2) + ' MB';
+ }
+ return (file.size / 1000).toFixed(2) + ' KB';
+ },
+
+ _hasError: function (file) {
+ if (file.error) {
+ return file.error;
+ }
+ // The number of added files is subtracted from
+ // maxNumberOfFiles before validation, so we check if
+ // maxNumberOfFiles is below 0 (instead of below 1):
+ if (this.options.maxNumberOfFiles < 0) {
+ return 'maxNumberOfFiles';
+ }
+ // Files are accepted if either the file type or the file name
+ // matches against the acceptFileTypes regular expression, as
+ // only browsers with support for the File API report the type:
+ if (!(this.options.acceptFileTypes.test(file.type) ||
+ this.options.acceptFileTypes.test(file.name))) {
+ return 'acceptFileTypes';
+ }
+ if (this.options.maxFileSize &&
+ file.size > this.options.maxFileSize) {
+ return 'maxFileSize';
+ }
+ if (typeof file.size === 'number' &&
+ file.size < this.options.minFileSize) {
+ return 'minFileSize';
+ }
+ return null;
+ },
+
+ _validate: function (files) {
+ var that = this,
+ valid = !!files.length;
+ $.each(files, function (index, file) {
+ file.error = that._hasError(file);
+ if (file.error) {
+ valid = false;
+ }
+ });
+ return valid;
+ },
+
+ _uploadTemplateHelper: function (file) {
+ file.sizef = this._formatFileSize(file);
+ return file;
+ },
+
+ _renderUploadTemplate: function (files) {
+ var that = this;
+ return $.tmpl(
+ this.options.uploadTemplate,
+ $.map(files, function (file) {
+ return that._uploadTemplateHelper(file);
+ })
+ );
+ },
+
+ _renderUpload: function (files) {
+ var that = this,
+ options = this.options,
+ tmpl = this._renderUploadTemplate(files),
+ isValidated = this._validate(files);
+ if (!(tmpl instanceof $)) {
+ return $();
+ }
+ tmpl.css('display', 'none');
+ // .slice(1).remove().end().first() removes all but the first
+ // element and selects only the first for the jQuery collection:
+ tmpl.find('.progress div').slice(
+ isValidated ? 1 : 0
+ ).remove().end().first()
+ .progressbar();
+ tmpl.find('.start button').slice(
+ this.options.autoUpload || !isValidated ? 0 : 1
+ ).remove().end().first()
+ .button({
+ text: false,
+ icons: {primary: 'ui-icon-circle-arrow-e'}
+ });
+ tmpl.find('.cancel button').slice(1).remove().end().first()
+ .button({
+ text: false,
+ icons: {primary: 'ui-icon-cancel'}
+ });
+ tmpl.find('.preview').each(function (index, node) {
+ that._loadImage(
+ files[index],
+ function (img) {
+ $(img).hide().appendTo(node).fadeIn();
+ },
+ {
+ maxWidth: options.previewMaxWidth,
+ maxHeight: options.previewMaxHeight,
+ fileTypes: options.previewFileTypes,
+ canvas: options.previewAsCanvas
+ }
+ );
+ });
+ return tmpl;
+ },
+
+ _downloadTemplateHelper: function (file) {
+ file.sizef = this._formatFileSize(file);
+ return file;
+ },
+
+ _renderDownloadTemplate: function (files) {
+ var that = this;
+ return $.tmpl(
+ this.options.downloadTemplate,
+ $.map(files, function (file) {
+ return that._downloadTemplateHelper(file);
+ })
+ );
+ },
+
+ _renderDownload: function (files) {
+ var tmpl = this._renderDownloadTemplate(files);
+ if (!(tmpl instanceof $)) {
+ return $();
+ }
+ tmpl.css('display', 'none');
+ tmpl.find('.delete button').button({
+ text: false,
+ icons: {primary: 'ui-icon-trash'}
+ });
+ tmpl.find('a').each(this._enableDragToDesktop);
+ return tmpl;
+ },
+
+ _startHandler: function (e) {
+ e.preventDefault();
+ var tmpl = $(this).closest('.template-upload'),
+ data = tmpl.data('data');
+ if (data && data.submit && !data.jqXHR) {
+ data.jqXHR = data.submit();
+ $(this).fadeOut();
+ }
+ },
+
+ _cancelHandler: function (e) {
+ e.preventDefault();
+ var tmpl = $(this).closest('.template-upload'),
+ data = tmpl.data('data') || {};
+ if (!data.jqXHR) {
+ data.errorThrown = 'abort';
+ e.data.fileupload._trigger('fail', e, data);
+ } else {
+ data.jqXHR.abort();
+ }
+ },
+
+ _deleteHandler: function (e) {
+ e.preventDefault();
+ var button = $(this);
+ e.data.fileupload._trigger('destroy', e, {
+ context: button.closest('.template-download'),
+ url: button.attr('data-url'),
+ type: button.attr('data-type'),
+ dataType: e.data.fileupload.options.dataType
+ });
+ },
+
+ _initEventHandlers: function () {
+ $.blueimp.fileupload.prototype._initEventHandlers.call(this);
+ var filesList = this.element.find('.files'),
+ eventData = {fileupload: this};
+ filesList.find('.start button')
+ .live(
+ 'click.' + this.options.namespace,
+ eventData,
+ this._startHandler
+ );
+ filesList.find('.cancel button')
+ .live(
+ 'click.' + this.options.namespace,
+ eventData,
+ this._cancelHandler
+ );
+ filesList.find('.delete button')
+ .live(
+ 'click.' + this.options.namespace,
+ eventData,
+ this._deleteHandler
+ );
+ },
+
+ _destroyEventHandlers: function () {
+ var filesList = this.element.find('.files');
+ filesList.find('.start button')
+ .die('click.' + this.options.namespace);
+ filesList.find('.cancel button')
+ .die('click.' + this.options.namespace);
+ filesList.find('.delete button')
+ .die('click.' + this.options.namespace);
+ $.blueimp.fileupload.prototype._destroyEventHandlers.call(this);
+ },
+
+ _initFileUploadButtonBar: function () {
+ var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'),
+ filesList = this.element.find('.files'),
+ ns = this.options.namespace;
+ fileUploadButtonBar
+ .addClass('ui-widget-header ui-corner-top');
+ this.element.find('.fileinput-button').each(function () {
+ var fileInput = $(this).find('input:file').detach();
+ $(this).button({icons: {primary: 'ui-icon-plusthick'}})
+ .append(fileInput);
+ });
+ fileUploadButtonBar.find('.start')
+ .button({icons: {primary: 'ui-icon-circle-arrow-e'}})
+ .bind('click.' + ns, function (e) {
+ e.preventDefault();
+ filesList.find('.start button').click();
+ });
+ fileUploadButtonBar.find('.cancel')
+ .button({icons: {primary: 'ui-icon-cancel'}})
+ .bind('click.' + ns, function (e) {
+ e.preventDefault();
+ filesList.find('.cancel button').click();
+ });
+ fileUploadButtonBar.find('.delete')
+ .button({icons: {primary: 'ui-icon-trash'}})
+ .bind('click.' + ns, function (e) {
+ e.preventDefault();
+ filesList.find('.delete button').click();
+ });
+ },
+
+ _destroyFileUploadButtonBar: function () {
+ this.element.find('.fileupload-buttonbar')
+ .removeClass('ui-widget-header ui-corner-top');
+ this.element.find('.fileinput-button').each(function () {
+ var fileInput = $(this).find('input:file').detach();
+ $(this).button('destroy')
+ .append(fileInput);
+ });
+ this.element.find('.fileupload-buttonbar button')
+ .unbind('click.' + this.options.namespace)
+ .button('destroy');
+ },
+
+ _enableFileInputButton: function () {
+ this.element.find('.fileinput-button input:file:disabled')
+ .each(function () {
+ var fileInput = $(this),
+ button = fileInput.parent();
+ fileInput.detach().prop('disabled', false);
+ button.button('enable').append(fileInput);
+ });
+ },
+
+ _disableFileInputButton: function () {
+ this.element.find('.fileinput-button input:file:enabled')
+ .each(function () {
+ var fileInput = $(this),
+ button = fileInput.parent();
+ fileInput.detach().prop('disabled', true);
+ button.button('disable').append(fileInput);
+ });
+ },
+
+ _initTemplates: function () {
+ // Handle cases where the templates are defined
+ // after the widget library has been included:
+ if (this.options.uploadTemplate instanceof $ &&
+ !this.options.uploadTemplate.length) {
+ this.options.uploadTemplate = $(
+ this.options.uploadTemplate.selector
+ );
+ }
+ if (this.options.downloadTemplate instanceof $ &&
+ !this.options.downloadTemplate.length) {
+ this.options.downloadTemplate = $(
+ this.options.downloadTemplate.selector
+ );
+ }
+ },
+
+ _create: function () {
+ $.blueimp.fileupload.prototype._create.call(this);
+ this._initTemplates();
+ this.element
+ .addClass('ui-widget');
+ this._initFileUploadButtonBar();
+ this.element.find('.fileupload-content')
+ .addClass('ui-widget-content ui-corner-bottom');
+ this.element.find('.fileupload-progressbar')
+ .hide().progressbar();
+ },
+
+ destroy: function () {
+ this.element.find('.fileupload-progressbar')
+ .progressbar('destroy');
+ this.element.find('.fileupload-content')
+ .removeClass('ui-widget-content ui-corner-bottom');
+ this._destroyFileUploadButtonBar();
+ this.element.removeClass('ui-widget');
+ $.blueimp.fileupload.prototype.destroy.call(this);
+ },
+
+ enable: function () {
+ $.blueimp.fileupload.prototype.enable.call(this);
+ this.element.find(':ui-button').not('.fileinput-button')
+ .button('enable');
+ this._enableFileInputButton();
+ },
+
+ disable: function () {
+ this.element.find(':ui-button').not('.fileinput-button')
+ .button('disable');
+ this._disableFileInputButton();
+ $.blueimp.fileupload.prototype.disable.call(this);
+ }
+
+ });
+
+}(jQuery));
760 app/assets/javascripts/jquery.fileupload.js
@@ -0,0 +1,760 @@
+/*
+ * jQuery File Upload Plugin 5.2.1
+ * https://github.com/blueimp/jQuery-File-Upload
+ *
+ * Copyright 2010, Sebastian Tschan
+ * https://blueimp.net
+ *
+ * Licensed under the MIT license:
+ * http://creativecommons.org/licenses/MIT/
+ */
+
+/*jslint nomen: true, unparam: true, regexp: true */
+/*global document, XMLHttpRequestUpload, Blob, File, FormData, location, jQuery */
+
+(function ($) {
+ 'use strict';
+
+ // The fileupload widget listens for change events on file input fields
+ // defined via fileInput setting and drop events of the given dropZone.
+ // In addition to the default jQuery Widget methods, the fileupload widget
+ // exposes the "add" and "send" methods, to add or directly send files
+ // using the fileupload API.
+ // By default, files added via file input selection, drag & drop or
+ // "add" method are uploaded immediately, but it is possible to override
+ // the "add" callback option to queue file uploads.
+ $.widget('blueimp.fileupload', {
+
+ options: {
+ // The namespace used for event handler binding on the dropZone and
+ // fileInput collections.
+ // If not set, the name of the widget ("fileupload") is used.
+ namespace: undefined,
+ // The drop target collection, by the default the complete document.
+ // Set to null or an empty collection to disable drag & drop support:
+ dropZone: $(document),
+ // The file input field collection, that is listened for change events.
+ // If undefined, it is set to the file input fields inside
+ // of the widget element on plugin initialization.
+ // Set to null or an empty collection to disable the change listener.
+ fileInput: undefined,
+ // By default, the file input field is replaced with a clone after
+ // each input field change event. This is required for iframe transport
+ // queues and allows change events to be fired for the same file
+ // selection, but can be disabled by setting the following option to false:
+ replaceFileInput: true,
+ // The parameter name for the file form data (the request argument name).
+ // If undefined or empty, the name property of the file input field is
+ // used, or "files[]" if the file input name property is also empty:
+ paramName: undefined,
+ // By default, each file of a selection is uploaded using an individual
+ // request for XHR type uploads. Set to false to upload file
+ // selections in one request each:
+ singleFileUploads: true,
+ // To limit the number of files uploaded with one XHR request,
+ // set the following option to an integer greater than 0:
+ limitMultiFileUploads: undefined,
+ // Set the following option to true to issue all file upload requests
+ // in a sequential order:
+ sequentialUploads: false,
+ // To limit the number of concurrent uploads,
+ // set the following option to an integer greater than 0:
+ limitConcurrentUploads: undefined,
+ // Set the following option to true to force iframe transport uploads:
+ forceIframeTransport: false,
+ // By default, XHR file uploads are sent as multipart/form-data.
+ // The iframe transport is always using multipart/form-data.
+ // Set to false to enable non-multipart XHR uploads:
+ multipart: true,
+ // To upload large files in smaller chunks, set the following option
+ // to a preferred maximum chunk size. If set to 0, null or undefined,
+ // or the browser does not support the required Blob API, files will
+ // be uploaded as a whole.
+ maxChunkSize: undefined,
+ // When a non-multipart upload or a chunked multipart upload has been
+ // aborted, this option can be used to resume the upload by setting
+ // it to the size of the already uploaded bytes. This option is most
+ // useful when modifying the options object inside of the "add" or
+ // "send" callbacks, as the options are cloned for each file upload.
+ uploadedBytes: undefined,
+ // By default, failed (abort or error) file uploads are removed from the
+ // global progress calculation. Set the following option to false to
+ // prevent recalculating the global progress data:
+ recalculateProgress: true,
+
+ // Additional form data to be sent along with the file uploads can be set
+ // using this option, which accepts an array of objects with name and
+ // value properties, a function returning such an array, a FormData
+ // object (for XHR file uploads), or a simple object.
+ // The form of the first fileInput is given as parameter to the function:
+ formData: function (form) {
+ return form.serializeArray();
+ },
+
+ // The add callback is invoked as soon as files are added to the fileupload
+ // widget (via file input selection, drag & drop or add API call).
+ // If the singleFileUploads option is enabled, this callback will be
+ // called once for each file in the selection for XHR file uplaods, else
+ // once for each file selection.
+ // The upload starts when the submit method is invoked on the data parameter.
+ // The data object contains a files property holding the added files
+ // and allows to override plugin options as well as define ajax settings.
+ // Listeners for this callback can also be bound the following way:
+ // .bind('fileuploadadd', func);
+ // data.submit() returns a Promise object and allows to attach additional
+ // handlers using jQuery's Deferred callbacks:
+ // data.submit().done(func).fail(func).always(func);
+ add: function (e, data) {
+ data.submit();
+ },
+
+ // Other callbacks:
+ // Callback for the start of each file upload request:
+ // send: function (e, data) {}, // .bind('fileuploadsend', func);
+ // Callback for successful uploads:
+ // done: function (e, data) {}, // .bind('fileuploaddone', func);
+ // Callback for failed (abort or error) uploads:
+ // fail: function (e, data) {}, // .bind('fileuploadfail', func);
+ // Callback for completed (success, abort or error) requests:
+ // always: function (e, data) {}, // .bind('fileuploadalways', func);
+ // Callback for upload progress events:
+ // progress: function (e, data) {}, // .bind('fileuploadprogress', func);
+ // Callback for global upload progress events:
+ // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
+ // Callback for uploads start, equivalent to the global ajaxStart event:
+ // start: function (e) {}, // .bind('fileuploadstart', func);
+ // Callback for uploads stop, equivalent to the global ajaxStop event:
+ // stop: function (e) {}, // .bind('fileuploadstop', func);
+ // Callback for change events of the fileInput collection:
+ // change: function (e, data) {}, // .bind('fileuploadchange', func);
+ // Callback for drop events of the dropZone collection:
+ // drop: function (e, data) {}, // .bind('fileuploaddrop', func);
+ // Callback for dragover events of the dropZone collection:
+ // dragover: function (e) {}, // .bind('fileuploaddragover', func);
+
+ // The plugin options are used as settings object for the ajax calls.
+ // The following are jQuery ajax settings required for the file uploads:
+ processData: false,
+ contentType: false,
+ cache: false
+ },
+
+ // A list of options that require a refresh after assigning a new value:
+ _refreshOptionsList: ['namespace', 'dropZone', 'fileInput'],
+
+ _isXHRUpload: function (options) {
+ var undef = 'undefined';
+ return !options.forceIframeTransport &&
+ typeof XMLHttpRequestUpload !== undef && typeof File !== undef &&
+ (!options.multipart || typeof FormData !== undef);
+ },
+
+ _getFormData: function (options) {
+ var formData;
+ if (typeof options.formData === 'function') {
+ return options.formData(options.form);
+ } else if ($.isArray(options.formData)) {
+ return options.formData;
+ } else if (options.formData) {
+ formData = [];
+ $.each(options.formData, function (name, value) {
+ formData.push({name: name, value: value});
+ });
+ return formData;
+ }
+ return [];
+ },
+
+ _getTotal: function (files) {
+ var total = 0;
+ $.each(files, function (index, file) {
+ total += file.size || 1;
+ });
+ return total;
+ },
+
+ _onProgress: function (e, data) {
+ if (e.lengthComputable) {
+ var total = data.total || this._getTotal(data.files),
+ loaded = parseInt(
+ e.loaded / e.total * (data.chunkSize || total),
+ 10
+ ) + (data.uploadedBytes || 0);
+ this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
+ data.lengthComputable = true;
+ data.loaded = loaded;
+ data.total = total;
+ // Trigger a custom progress event with a total data property set
+ // to the file size(s) of the current upload and a loaded data
+ // property calculated accordingly:
+ this._trigger('progress', e, data);
+ // Trigger a global progress event for all current file uploads,
+ // including ajax calls queued for sequential file uploads:
+ this._trigger('progressall', e, {
+ lengthComputable: true,
+ loaded: this._loaded,
+ total: this._total
+ });
+ }
+ },
+
+ _initProgressListener: function (options) {
+ var that = this,
+ xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
+ // Accesss to the native XHR object is required to add event listeners
+ // for the upload progress event:
+ if (xhr.upload && xhr.upload.addEventListener) {
+ xhr.upload.addEventListener('progress', function (e) {
+ that._onProgress(e, options);
+ }, false);
+ options.xhr = function () {
+ return xhr;
+ };
+ }
+ },
+
+ _initXHRData: function (options) {
+ var formData,
+ file = options.files[0];
+ if (!options.multipart || options.blob) {
+ // For non-multipart uploads and chunked uploads,
+ // file meta data is not part of the request body,
+ // so we transmit this data as part of the HTTP headers.
+ // For cross domain requests, these headers must be allowed
+ // via Access-Control-Allow-Headers or removed using
+ // the beforeSend callback:
+ options.headers = $.extend(options.headers, {
+ 'X-File-Name': file.name,
+ 'X-File-Type': file.type,
+ 'X-File-Size': file.size
+ });
+ if (!options.blob) {
+ // Non-chunked non-multipart upload:
+ options.contentType = file.type;
+ options.data = file;
+ } else if (!options.multipart) {
+ // Chunked non-multipart upload:
+ options.contentType = 'application/octet-stream';
+ options.data = options.blob;
+ }
+ }
+ if (options.multipart && typeof FormData !== 'undefined') {
+ if (options.formData instanceof FormData) {
+ formData = options.formData;
+ } else {
+ formData = new FormData();
+ $.each(this._getFormData(options), function (index, field) {
+ formData.append(field.name, field.value);
+ });
+ }
+ if (options.blob) {
+ formData.append(options.paramName, options.blob);
+ } else {
+ $.each(options.files, function (index, file) {
+ // File objects are also Blob instances.
+ // This check allows the tests to run with
+ // dummy objects:
+ if (file instanceof Blob) {
+ formData.append(options.paramName, file);
+ }
+ });
+ }
+ options.data = formData;
+ }
+ // Blob reference is not needed anymore, free memory:
+ options.blob = null;
+ },
+
+ _initIframeSettings: function (options) {
+ // Setting the dataType to iframe enables the iframe transport:
+ options.dataType = 'iframe ' + (options.dataType || '');
+ // The iframe transport accepts a serialized array as form data:
+ options.formData = this._getFormData(options);
+ },
+
+ _initDataSettings: function (options) {
+ if (this._isXHRUpload(options)) {
+ if (!this._chunkedUpload(options, true)) {
+ if (!options.data) {
+ this._initXHRData(options);
+ }
+ this._initProgressListener(options);
+ }
+ } else {
+ this._initIframeSettings(options);
+ }
+ },
+
+ _initFormSettings: function (options) {
+ // Retrieve missing options from the input field and the
+ // associated form, if available:
+ if (!options.form || !options.form.length) {
+ options.form = $(options.fileInput.prop('form'));
+ }
+ if (!options.paramName) {
+ options.paramName = options.fileInput.prop('name') ||
+ 'files[]';
+ }
+ if (!options.url) {
+ options.url = options.form.prop('action') || location.href;
+ }
+ // The HTTP request method must be "POST" or "PUT":
+ options.type = (options.type || options.form.prop('method') || '')
+ .toUpperCase();
+ if (options.type !== 'POST' && options.type !== 'PUT') {
+ options.type = 'POST';
+ }
+ },
+
+ _getAJAXSettings: function (data) {
+ var options = $.extend({}, this.options, data);
+ this._initFormSettings(options);
+ this._initDataSettings(options);
+ return options;
+ },
+
+ // Maps jqXHR callbacks to the equivalent
+ // methods of the given Promise object:
+ _enhancePromise: function (promise) {
+ promise.success = promise.done;
+ promise.error = promise.fail;
+ promise.complete = promise.always;
+ return promise;
+ },
+
+ // Creates and returns a Promise object enhanced with
+ // the jqXHR methods abort, success, error and complete:
+ _getXHRPromise: function (resolveOrReject, context, args) {
+ var dfd = $.Deferred(),
+ promise = dfd.promise();
+ context = context || this.options.context || promise;
+ if (resolveOrReject === true) {
+ dfd.resolveWith(context, args);
+ } else if (resolveOrReject === false) {
+ dfd.rejectWith(context, args);
+ }
+ promise.abort = dfd.promise;
+ return this._enhancePromise(promise);
+ },
+
+ // Uploads a file in multiple, sequential requests
+ // by splitting the file up in multiple blob chunks.
+ // If the second parameter is true, only tests if the file
+ // should be uploaded in chunks, but does not invoke any
+ // upload requests:
+ _chunkedUpload: function (options, testOnly) {
+ var that = this,
+ file = options.files[0],
+ fs = file.size,
+ ub = options.uploadedBytes = options.uploadedBytes || 0,
+ mcs = options.maxChunkSize || fs,
+ // Use the Blob methods with the slice implementation
+ // according to the W3C Blob API specification:
+ slice = file.webkitSlice || file.mozSlice || file.slice,
+ upload,
+ n,
+ jqXHR,
+ pipe;
+ if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
+ options.data) {
+ return false;
+ }
+ if (testOnly) {
+ return true;
+ }
+ if (ub >= fs) {
+ file.error = 'uploadedBytes';
+ return this._getXHRPromise(false);
+ }
+ // n is the number of blobs to upload,
+ // calculated via filesize, uploaded bytes and max chunk size:
+ n = Math.ceil((fs - ub) / mcs);
+ // The chunk upload method accepting the chunk number as parameter:
+ upload = function (i) {
+ if (!i) {
+ return that._getXHRPromise(true);
+ }
+ // Upload the blobs in sequential order:
+ return upload(i -= 1).pipe(function () {
+ // Clone the options object for each chunk upload:
+ var o = $.extend({}, options);
+ o.blob = slice.call(
+ file,
+ ub + i * mcs,
+ ub + (i + 1) * mcs
+ );
+ // Store the current chunk size, as the blob itself
+ // will be dereferenced after data processing:
+ o.chunkSize = o.blob.size;
+ // Process the upload data (the blob and potential form data):
+ that._initXHRData(o);
+ // Add progress listeners for this chunk upload:
+ that._initProgressListener(o);
+ jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
+ .done(function () {
+ // Create a progress event if upload is done and
+ // no progress event has been invoked for this chunk:
+ if (!o.loaded) {
+ that._onProgress($.Event('progress', {
+ lengthComputable: true,
+ loaded: o.chunkSize,
+ total: o.chunkSize
+ }), o);
+ }
+ options.uploadedBytes = o.uploadedBytes
+ += o.chunkSize;
+ });
+ return jqXHR;
+ });
+ };
+ // Return the piped Promise object, enhanced with an abort method,
+ // which is delegated to the jqXHR object of the current upload,
+ // and jqXHR callbacks mapped to the equivalent Promise methods:
+ pipe = upload(n);
+ pipe.abort = function () {
+ return jqXHR.abort();
+ };
+ return this._enhancePromise(pipe);
+ },
+
+ _beforeSend: function (e, data) {
+ if (this._active === 0) {
+ // the start callback is triggered when an upload starts
+ // and no other uploads are currently running,
+ // equivalent to the global ajaxStart event:
+ this._trigger('start');
+ }
+ this._active += 1;
+ // Initialize the global progress values:
+ this._loaded += data.uploadedBytes || 0;
+ this._total += this._getTotal(data.files);
+ },
+
+ _onDone: function (result, textStatus, jqXHR, options) {
+ if (!this._isXHRUpload(options)) {
+ // Create a progress event for each iframe load:
+ this._onProgress($.Event('progress', {
+ lengthComputable: true,
+ loaded: 1,
+ total: 1
+ }), options);
+ }
+ options.result = result;
+ options.textStatus = textStatus;
+ options.jqXHR = jqXHR;
+ this._trigger('done', null, options);
+ },
+
+ _onFail: function (jqXHR, textStatus, errorThrown, options) {
+ options.jqXHR = jqXHR;
+ options.textStatus = textStatus;
+ options.errorThrown = errorThrown;
+ this._trigger('fail', null, options);
+ if (options.recalculateProgress) {
+ // Remove the failed (error or abort) file upload from
+ // the global progress calculation:
+ this._loaded -= options.loaded || options.uploadedBytes || 0;
+ this._total -= options.total || this._getTotal(options.files);
+ }
+ },
+
+ _onAlways: function (result, textStatus, jqXHR, errorThrown, options) {
+ this._active -= 1;
+ options.result = result;
+ options.textStatus = textStatus;
+ options.jqXHR = jqXHR;
+ options.errorThrown = errorThrown;
+ this._trigger('always', null, options);
+ if (this._active === 0) {
+ // The stop callback is triggered when all uploads have
+ // been completed, equivalent to the global ajaxStop event:
+ this._trigger('stop');
+ // Reset the global progress values:
+ this._loaded = this._total = 0;
+ }
+ },
+
+ _onSend: function (e, data) {
+ var that = this,
+ jqXHR,
+ slot,
+ pipe,
+ options = that._getAJAXSettings(data),
+ send = function (resolve, args) {
+ that._sending += 1;
+ jqXHR = jqXHR || (
+ (resolve !== false &&
+ that._trigger('send', e, options) !== false &&
+ (that._chunkedUpload(options) || $.ajax(options))) ||
+ that._getXHRPromise(false, options.context, args)
+ ).done(function (result, textStatus, jqXHR) {
+ that._onDone(result, textStatus, jqXHR, options);
+ }).fail(function (jqXHR, textStatus, errorThrown) {
+ that._onFail(jqXHR, textStatus, errorThrown, options);
+ }).always(function (a1, a2, a3) {
+ that._sending -= 1;
+ if (a3 && a3.done) {
+ that._onAlways(a1, a2, a3, undefined, options);
+ } else {
+ that._onAlways(undefined, a2, a1, a3, options);
+ }
+ if (options.limitConcurrentUploads &&
+ options.limitConcurrentUploads > that._sending) {
+ // Start the next queued upload,
+ // that has not been aborted:
+ var nextSlot = that._slots.shift();
+ while (nextSlot) {
+ if (!nextSlot.isRejected()) {
+ nextSlot.resolve();
+ break;
+ }
+ nextSlot = that._slots.shift();
+ }
+ }
+ });
+ return jqXHR;
+ };
+ this._beforeSend(e, options);
+ if (this.options.sequentialUploads ||
+ (this.options.limitConcurrentUploads &&
+ this.options.limitConcurrentUploads <= this._sending)) {
+ if (this.options.limitConcurrentUploads > 1) {
+ slot = $.Deferred();
+ this._slots.push(slot);
+ pipe = slot.pipe(send);
+ } else {
+ pipe = (this._sequence = this._sequence.pipe(send, send));
+ }
+ // Return the piped Promise object, enhanced with an abort method,
+ // which is delegated to the jqXHR object of the current upload,
+ // and jqXHR callbacks mapped to the equivalent Promise methods:
+ pipe.abort = function () {
+ var args = [undefined, 'abort', 'abort'];
+ if (!jqXHR) {
+ if (slot) {
+ slot.rejectWith(args);
+ }
+ return send(false, args);
+ }
+ return jqXHR.abort();
+ };
+ return this._enhancePromise(pipe);
+ }
+ return send();
+ },
+
+ _onAdd: function (e, data) {
+ var that = this,
+ result = true,
+ options = $.extend({}, this.options, data),
+ fileSet = data.files,
+ limit = options.limitMultiFileUploads,
+ i;
+ if (!(options.singleFileUploads || limit) ||
+ !this._isXHRUpload(options)) {
+ fileSet = [fileSet];
+ } else if (!options.singleFileUploads && limit) {
+ fileSet = [];
+ for (i = 0; i < data.files.length; i += limit) {
+ fileSet.push(data.files.slice(i, i + limit));
+ }
+ }
+ $.each(fileSet, function (index, file) {
+ var files = $.isArray(file) ? file : [file],
+ newData = $.extend({}, data, {files: files});
+ newData.submit = function () {
+ return that._onSend(e, newData);
+ };
+ return (result = that._trigger('add', e, newData));
+ });
+ return result;
+ },
+
+ // File Normalization for Gecko 1.9.1 (Firefox 3.5) support:
+ _normalizeFile: function (index, file) {
+ if (file.name === undefined && file.size === undefined) {
+ file.name = file.fileName;
+ file.size = file.fileSize;
+ }
+ },
+
+ _replaceFileInput: function (input) {
+ var inputClone = input.clone(true);
+ $('<form></form>').append(inputClone)[0].reset();
+ // Detaching allows to insert the fileInput on another form
+ // without loosing the file input value:
+ input.after(inputClone).detach();
+ // Avoid memory leaks with the detached file input:
+ $.cleanData(input.unbind('remove'));
+ // Replace the original file input element in the fileInput
+ // collection with the clone, which has been copied including
+ // event handlers:
+ this.options.fileInput = this.options.fileInput.map(function (i, el) {
+ if (el === input[0]) {
+ return inputClone[0];
+ }
+ return el;
+ });
+ // If the widget has been initialized on the file input itself,
+ // override this.element with the file input clone:
+ if (input[0] === this.element[0]) {
+ this.element = inputClone;
+ }
+ },
+
+ _onChange: function (e) {
+ var that = e.data.fileupload,
+ data = {
+ files: $.each($.makeArray(e.target.files), that._normalizeFile),
+ fileInput: $(e.target),
+ form: $(e.target.form)
+ };
+ if (!data.files.length) {
+ // If the files property is not available, the browser does not
+ // support the File API and we add a pseudo File object with
+ // the input value as name with path information removed:
+ data.files = [{name: e.target.value.replace(/^.*\\/, '')}];
+ }
+ if (that.options.replaceFileInput) {
+ that._replaceFileInput(data.fileInput);
+ }
+ if (that._trigger('change', e, data) === false ||
+ that._onAdd(e, data) === false) {
+ return false;
+ }
+ },
+
+ _onDrop: function (e) {
+ var that = e.data.fileupload,
+ dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
+ data = {
+ files: $.each(
+ $.makeArray(dataTransfer && dataTransfer.files),
+ that._normalizeFile
+ )
+ };
+ if (that._trigger('drop', e, data) === false ||
+ that._onAdd(e, data) === false) {
+ return false;
+ }
+ e.preventDefault();
+ },
+
+ _onDragOver: function (e) {
+ var that = e.data.fileupload,
+ dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
+ if (that._trigger('dragover', e) === false) {
+ return false;
+ }
+ if (dataTransfer) {
+ dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy';
+ }
+ e.preventDefault();
+ },
+
+ _initEventHandlers: function () {
+ var ns = this.options.namespace || this.widgetName;
+ this.options.dropZone
+ .bind('dragover.' + ns, {fileupload: this}, this._onDragOver)
+ .bind('drop.' + ns, {fileupload: this}, this._onDrop);
+ this.options.fileInput
+ .bind('change.' + ns, {fileupload: this}, this._onChange);
+ },
+
+ _destroyEventHandlers: function () {
+ var ns = this.options.namespace || this.widgetName;
+ this.options.dropZone
+ .unbind('dragover.' + ns, this._onDragOver)
+ .unbind('drop.' + ns, this._onDrop);
+ this.options.fileInput
+ .unbind('change.' + ns, this._onChange);
+ },
+
+ _beforeSetOption: function (key, value) {
+ this._destroyEventHandlers();
+ },
+
+ _afterSetOption: function (key, value) {
+ var options = this.options;
+ if (!options.fileInput) {
+ options.fileInput = $();
+ }
+ if (!options.dropZone) {
+ options.dropZone = $();
+ }
+ this._initEventHandlers();
+ },
+
+ _setOption: function (key, value) {
+ var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
+ if (refresh) {
+ this._beforeSetOption(key, value);
+ }
+ $.Widget.prototype._setOption.call(this, key, value);
+ if (refresh) {
+ this._afterSetOption(key, value);
+ }
+ },
+
+ _create: function () {
+ var options = this.options;
+ if (options.fileInput === undefined) {
+ options.fileInput = this.element.is('input:file') ?
+ this.element : this.element.find('input:file');
+ } else if (!options.fileInput) {
+ options.fileInput = $();
+ }
+ if (!options.dropZone) {
+ options.dropZone = $();
+ }
+ this._slots = [];
+ this._sequence = this._getXHRPromise(true);
+ this._sending = this._active = this._loaded = this._total = 0;
+ this._initEventHandlers();
+ },
+
+ destroy: function () {
+ this._destroyEventHandlers();
+ $.Widget.prototype.destroy.call(this);
+ },
+
+ enable: function () {
+ $.Widget.prototype.enable.call(this);
+ this._initEventHandlers();
+ },
+
+ disable: function () {
+ this._destroyEventHandlers();
+ $.Widget.prototype.disable.call(this);
+ },
+
+ // This method is exposed to the widget API and allows adding files
+ // using the fileupload API. The data parameter accepts an object which
+ // must have a files property and can contain additional options:
+ // .fileupload('add', {files: filesList});
+ add: function (data) {
+ if (!data || this.options.disabled) {
+ return;
+ }
+ data.files = $.each($.makeArray(data.files), this._normalizeFile);
+ this._onAdd(null, data);
+ },
+
+ // This method is exposed to the widget API and allows sending files
+ // using the fileupload API. The data parameter accepts an object which
+ // must have a files property and can contain additional options:
+ // .fileupload('send', {files: filesList});
+ // The method returns a Promise object for the file upload call.
+ send: function (data) {
+ if (data && !this.options.disabled) {
+ data.files = $.each($.makeArray(data.files), this._normalizeFile);
+ if (data.files.length) {
+ return this._onSend(null, data);
+ }
+ }
+ return this._getXHRPromise(false, data && data.context);
+ }
+
+ });
+
+}(jQuery));
156 app/assets/javascripts/jquery.iframe-transport.js
@@ -0,0 +1,156 @@
+/*
+ * jQuery Iframe Transport Plugin 1.2.2
+ * https://github.com/blueimp/jQuery-File-Upload
+ *
+ * Copyright 2011, Sebastian Tschan
+ * https://blueimp.net
+ *
+ * Licensed under the MIT license:
+ * http://creativecommons.org/licenses/MIT/
+ */
+
+/*jslint unparam: true */
+/*global jQuery */
+
+(function ($) {
+ 'use strict';
+
+ // Helper variable to create unique names for the transport iframes:
+ var counter = 0;
+
+ // The iframe transport accepts three additional options:
+ // options.fileInput: a jQuery collection of file input fields
+ // options.paramName: the parameter name for the file form data,
+ // overrides the name property of the file input field(s)
+ // options.formData: an array of objects with name and value properties,
+ // equivalent to the return data of .serializeArray(), e.g.:
+ // [{name: a, value: 1}, {name: b, value: 2}]
+ $.ajaxTransport('iframe', function (options, originalOptions, jqXHR) {
+ if (options.type === 'POST' || options.type === 'GET') {
+ var form,
+ iframe;
+ return {
+ send: function (headers, completeCallback) {
+ form = $('<form style="display:none;"></form>');
+ // javascript:false as initial iframe src
+ // prevents warning popups on HTTPS in IE6.
+ // IE versions below IE8 cannot set the name property of
+ // elements that have already been added to the DOM,
+ // so we set the name along with the iframe HTML markup:
+ iframe = $(
+ '<iframe src="javascript:false;" name="iframe-transport-' +
+ (counter += 1) + '"></iframe>'
+ ).bind('load', function () {
+ var fileInputClones;
+ iframe
+ .unbind('load')
+ .bind('load', function () {
+ var response;
+ // Wrap in a try/catch block to catch exceptions thrown
+ // when trying to access cross-domain iframe contents:
+ try {
+ response = iframe.contents();
+ // Google Chrome and Firefox do not throw an
+ // exception when calling iframe.contents() on
+ // cross-domain requests, so we unify the response:
+ if (!response.length || !response[0].firstChild) {
+ throw new Error();
+ }
+ } catch (e) {
+ response = undefined;
+ }
+ // The complete callback returns the
+ // iframe content document as response object:
+ completeCallback(
+ 200,
+ 'success',
+ {'iframe': response}
+ );
+ // Fix for IE endless progress bar activity bug
+ // (happens on form submits to iframe targets):
+ $('<iframe src="javascript:false;"></iframe>')
+ .appendTo(form);
+ form.remove();
+ });
+ form
+ .prop('target', iframe.prop('name'))
+ .prop('action', options.url)
+ .prop('method', options.type);
+ if (options.formData) {
+ $.each(options.formData, function (index, field) {
+ $('<input type="hidden"/>')
+ .prop('name', field.name)
+ .val(field.value)
+ .appendTo(form);
+ });
+ }
+ if (options.fileInput && options.fileInput.length &&
+ options.type === 'POST') {
+ fileInputClones = options.fileInput.clone();
+ // Insert a clone for each file input field:
+ options.fileInput.after(function (index) {
+ return fileInputClones[index];
+ });
+ if (options.paramName) {
+ options.fileInput.each(function () {
+ $(this).prop('name', options.paramName);
+ });
+ }
+ // Appending the file input fields to the hidden form
+ // removes them from their original location:
+ form
+ .append(options.fileInput)
+ .prop('enctype', 'multipart/form-data')
+ // enctype must be set as encoding for IE:
+ .prop('encoding', 'multipart/form-data');
+ }
+ form.submit();
+ // Insert the file input fields at their original location
+ // by replacing the clones with the originals:
+ if (fileInputClones && fileInputClones.length) {
+ options.fileInput.each(function (index, input) {
+ var clone = $(fileInputClones[index]);
+ $(input).prop('name', clone.prop('name'));
+ clone.replaceWith(input);
+ });
+ }
+ });
+ form.append(iframe).appendTo('body');
+ },
+ abort: function () {
+ if (iframe) {
+ // javascript:false as iframe src aborts the request
+ // and prevents warning popups on HTTPS in IE6.
+ // concat is used to avoid the "Script URL" JSLint error:
+ iframe
+ .unbind('load')
+ .prop('src', 'javascript'.concat(':false;'));
+ }
+ if (form) {
+ form.remove();
+ }
+ }
+ };
+ }
+ });
+
+ // The iframe transport returns the iframe content document as response.
+ // The following adds converters from iframe to text, json, html, and script:
+ $.ajaxSetup({
+ converters: {
+ 'iframe text': function (iframe) {
+ return iframe.text();
+ },
+ 'iframe json': function (iframe) {
+ return $.parseJSON(iframe.text());
+ },
+ 'iframe html': function (iframe) {
+ return iframe.find('body').html();
+ },
+ 'iframe script': function (iframe) {
+ return $.globalEval(iframe.text());
+ }
+ }
+ });
+
+}(jQuery));
3 app/assets/javascripts/pictures.js.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
7 app/assets/stylesheets/application.css
@@ -0,0 +1,7 @@
+/*
+ * This is a manifest file that'll automatically include all the stylesheets available in this directory
+ * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
+ * the top of the compiled file, but it's generally better to create a new file per style scope.
+ *= require_self
+ *= require_tree .
+*/
100 app/assets/stylesheets/jquery.fileupload-ui.css
@@ -0,0 +1,100 @@
+@charset 'UTF-8';
+/*
+ * jQuery File Upload UI Plugin CSS 5.0.6
+ * https://github.com/blueimp/jQuery-File-Upload
+ *
+ * Copyright 2010, Sebastian Tschan
+ * https://blueimp.net
+ *
+ * Licensed under the MIT license:
+ * http://creativecommons.org/licenses/MIT/
+ */
+
+.fileupload-buttonbar .ui-button input {
+ position: absolute;
+ top: 0;
+ right: 0;
+ margin: 0;
+ border: solid transparent;
+ border-width: 0 0 100px 200px;
+ opacity: 0;
+ filter: alpha(opacity=0);
+ -o-transform: translate(250px, -50px) scale(1);
+ -moz-transform: translate(-300px, 0) scale(4);
+ direction: ltr;
+ cursor: pointer;
+}
+
+.fileinput-button {
+ overflow: hidden;
+}
+
+/* Fix for IE 6: */
+*html .fileinput-button {
+ padding: 2px 0;
+}
+
+/* Fix for IE 7: */
+*+html .fileinput-button {
+ padding: 2px 0;
+}
+
+.fileupload-buttonbar {
+ padding: 0.2em 0.4em;
+}
+
+.fileupload-buttonbar .ui-button {
+ vertical-align: middle;
+}
+
+.fileupload-content {
+ padding: 0.2em 0.4em;
+ border-top-width: 0;
+}
+
+.fileupload-content .ui-progressbar {
+ width: 200px;
+ height: 20px;
+}
+
+.fileupload-content .ui-progressbar-value {
+ background: url(pbar-ani.gif);
+}
+
+.fileupload-content .fileupload-progressbar {
+ width: 400px;
+ margin: 10px 0;
+}
+
+.files {
+ margin: 10px 0;
+ border-collapse: collapse;
+}
+
+.files td {
+ padding: 5px;
+ border-spacing: 5px;
+}
+
+.files img {
+ border: none;
+}
+
+.files .name {
+ padding: 0 10px;
+}
+
+.files .size {
+ padding: 0 10px 0 0;
+ text-align: right;
+ white-space: nowrap;
+}
+
+.ui-state-disabled .ui-state-disabled {
+ opacity: 1;
+ filter: alpha(opacity=100);
+}
+
+.ui-state-disabled input {
+ cursor: default;
+}
3 app/assets/stylesheets/pictures.css.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the Pictures controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
56 app/assets/stylesheets/scaffolds.css.scss
@@ -0,0 +1,56 @@
+body {
+ background-color: #fff;
+ color: #333;
+ font-family: verdana, arial, helvetica, sans-serif;
+ font-size: 13px;
+ line-height: 18px; }
+
+p, ol, ul, td {
+ font-family: verdana, arial, helvetica, sans-serif;
+ font-size: 13px;
+ line-height: 18px; }
+
+pre {
+ background-color: #eee;
+ padding: 10px;
+ font-size: 11px; }
+
+a {
+ color: #000;
+ &:visited {
+ color: #666; }
+ &:hover {
+ color: #fff;
+ background-color: #000; } }
+
+div {
+ &.field, &.actions {
+ margin-bottom: 10px; } }
+
+#notice {
+ color: green; }
+
+.field_with_errors {
+ padding: 2px;
+ background-color: red;
+ display: table; }
+
+#error_explanation {
+ width: 450px;
+ border: 2px solid red;
+ padding: 7px;
+ padding-bottom: 0;
+ margin-bottom: 20px;
+ background-color: #f0f0f0;
+ h2 {
+ text-align: left;
+ font-weight: bold;
+ padding: 5px 5px 5px 15px;
+ font-size: 12px;
+ margin: -7px;
+ margin-bottom: 0px;
+ background-color: #c00;
+ color: #fff; }
+ ul li {
+ font-size: 12px;
+ list-style: square; } }
3 app/controllers/application_controller.rb
@@ -0,0 +1,3 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+end
83 app/controllers/pictures_controller.rb
@@ -0,0 +1,83 @@
+class PicturesController < ApplicationController
+ # GET /pictures
+ # GET /pictures.json
+ def index
+ @pictures = Picture.all
+
+ respond_to do |format|
+ format.html # index.html.erb
+ format.json { render json: @pictures }
+ end
+ end
+
+ # GET /pictures/1
+ # GET /pictures/1.json
+ def show
+ @picture = Picture.find(params[:id])
+
+ respond_to do |format|
+ format.html # show.html.erb
+ format.json { render json: @picture }
+ end
+ end
+
+ # GET /pictures/new
+ # GET /pictures/new.json
+ def new
+ @picture = Picture.new
+
+ respond_to do |format|