diff --git a/Gemfile b/Gemfile index 86521b1..a0fbb16 100644 --- a/Gemfile +++ b/Gemfile @@ -1,5 +1,5 @@ source "https://rubygems.org" -gem 'rails', '~> 4.0' +gem 'rails', '~> 4.1' gem 'minitest', '~> 3.2.0' gem 'fast_gettext', '~> 0.6.8' gem 'acts-as-taggable-on', '~> 3.4.2' @@ -7,11 +7,14 @@ gem 'rails_autolink', '~> 1.1.5' gem 'pg', '~> 0.13.2' gem 'rmagick', '~> 2.13.1' gem 'RedCloth', '~> 4.2.9' -gem 'will_paginate', '~> 3.0.3' gem 'ruby-feedparser', '~> 0.7' gem 'daemons', '~> 1.1.5' gem 'thin', '~> 1.3.1' gem 'nokogiri', '~> 1.5.5' +gem 'will_paginate' +gem 'pothoven-attachment_fu' +gem 'delayed_job' +gem 'delayed_job_active_record' gem 'rake', :require => false gem 'rest-client', '~> 1.6.7' gem 'exception_notification', '~> 4.0.1' @@ -30,6 +33,7 @@ gem 'rails-observers' gem 'actionpack-page_caching' gem 'actionpack-action_caching' gem 'activerecord-session_store' +gem 'activerecord-deprecated_finders', require: 'active_record/deprecated_finders' # FIXME list here all actual dependencies (i.e. the ones in debian/control), diff --git a/vendor/plugins/delayed_job/.rspec b/vendor/plugins/delayed_job/.rspec deleted file mode 100644 index 0ea59b0..0000000 --- a/vendor/plugins/delayed_job/.rspec +++ /dev/null @@ -1,3 +0,0 @@ ---color ---fail-fast ---order random diff --git a/vendor/plugins/delayed_job/.travis.yml b/vendor/plugins/delayed_job/.travis.yml deleted file mode 100644 index c3148f2..0000000 --- a/vendor/plugins/delayed_job/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -language: ruby -only: - - master -rvm: - - jruby-19mode - - rbx-19mode - - 1.9.2 - - 1.9.3 - - 2.0.0 -env: - matrix: - - "RAILS_VERSION=\"~> 3.0.0\"" - - "RAILS_VERSION=\"~> 3.1.0\"" - - "RAILS_VERSION=\"~> 3.2.0\"" - - "RAILS_VERSION=\"~> 4.0.0\"" -matrix: - exclude: - - rvm: 1.9.2 - env: "RAILS_VERSION=\"~> 4.0.0\"" - allow_failures: - - rvm: jruby-19mode - - rvm: rbx-19mode \ No newline at end of file diff --git a/vendor/plugins/delayed_job/CHANGELOG.md b/vendor/plugins/delayed_job/CHANGELOG.md deleted file mode 100644 index e898264..0000000 --- a/vendor/plugins/delayed_job/CHANGELOG.md +++ /dev/null @@ -1,170 +0,0 @@ -4.0.0 - 2013-07-30 -================== -* Rails 4 compatibility -* Reverted threaded startup due to daemons incompatibilities -* Attempt to recover from job reservation errors - -4.0.0.beta2 - 2013-05-28 -======================== -* Rails 4 compatibility -* Threaded startup script for faster multi-worker startup -* YAML compatibility changes -* Added jobs:check rake task - -4.0.0.beta1 - 2013-03-02 -======================== -* Rails 4 compatibility - -3.0.5 - 2013-01-28 -================== -* Better job timeout error logging -* psych support for delayed_job_data_mapper deserialization -* User can configure the worker to raise a SignalException on TERM and/or INT -* Add the ability to run all available jobs and exit when complete - -3.0.4 - 2012-11-09 -================== -* Allow the app to specify a default queue name -* Capistrano script now allows user to specify the DJ command, allowing the user to add "bundle exec" if necessary -* Persisted record check is now more general - -3.0.3 - 2012-05-25 -================== -* Fix a bug where the worker would not respect the exit condition -* Properly handle sleep delay command line argument - -3.0.2 - 2012-04-02 -================== -* Fix deprecation warnings -* Raise ArgumentError if attempting to enqueue a performable method on an object that hasn't been persisted yet -* Allow the number of jobs read at a time to be configured from the command line using --read-ahead -* Allow custom logger to be configured through Delayed::Worker.logger -* Various documentation improvements - -3.0.1 - 2012-01-24 -================== -* Added RecordNotFound message to deserialization error -* Direct JRuby's yecht parser to syck extensions -* Updated psych extensions for better compatibility with ruby 1.9.2 -* Updated syck extension for increased compatibility with class methods -* Test grooming - -3.0.0 - 2011-12-30 -================== -* New: Named queues -* New: Job/Worker lifecycle callbacks -* Change: daemons is no longer a runtime dependency -* Change: Active Record backend support is provided by a separate gem -* Change: Enqueue hook is called before jobs are saved so that they may be modified -* Fix problem deserializing models that use a custom primary key column -* Fix deserializing AR models when the object isn't in the default scope -* Fix hooks not getting called when delay_jobs is false - -2.1.4 - 2011-02-11 -================== -* Working around issues when psych is loaded, fixes issues with bundler 1.0.10 and Rails 3.0.4 -* Added -p/--prefix option to help differentiate multiple delayed job workers on the same host. - -2.1.3 - 2011-01-20 -================== -* Revert worker contention fix due to regressions -* Added Delayed::Worker.delay_jobs flag to support running jobs immediately - -2.1.2 - 2010-12-01 -================== -* Remove contention between multiple workers by performing an update to lock a job before fetching it -* Job payloads may implement #max_attempts to control how many times it should be retried -* Fix for loading ActionMailer extension -* Added 'delayed_job_server_role' Capistrano variable to allow delayed_job to run on its own worker server - set :delayed_job_server_role, :worker -* Fix `rake jobs:work` so it outputs to the console - -2.1.1 - 2010-11-14 -================== -* Fix issue with worker name not getting properly set when locking a job -* Fixes for YAML serialization - -2.1.0 - 2010-11-14 -================== -* Added enqueue, before, after, success, error, and failure. See the README -* Remove Merb support -* Remove all non Active Record backends into separate gems. See https://github.com/collectiveidea/delayed_job/wiki/Backends -* remove rails 2 support. delayed_job 2.1 will only support Rails 3 -* New pure-YAML serialization -* Added Rails 3 railtie and generator -* Changed @@sleep_delay to self.class.sleep_delay to be consistent with other class variable usage -* Added --sleep-delay command line option - -2.0.8 - Unreleased -================== -* Backport fix for deserialization errors that bring down the daemon - -2.0.7 - 2011-02-10 -================== -* Fixed missing generators and recipes for Rails 2.x - -2.0.6 - 2011-01-20 -================== -* Revert worker contention fix due to regressions - -2.0.5 - 2010-12-01 -================== -* Added #reschedule_at hook on payload to determine when the job should be rescheduled [backported from 2.1] -* Added --sleep-delay command line option [backported from 2.1] -* Added 'delayed_job_server_role' Capistrano variable to allow delayed_job to run on its own worker server - set :delayed_job_server_role, :worker -* Changed AR backend to reserve jobs using an UPDATE query to reduce worker contention [backported from 2.1] - -2.0.4 - 2010-11-14 -================== -* Fix issue where dirty tracking prevented job from being properly unlocked -* Add delayed_job_args variable for Capistrano recipe to allow configuration of started workers (e.g. "-n 2 --max-priority 10") -* Added options to handle_asynchronously -* Added Delayed::Worker.default_priority -* Allow private methods to be delayed -* Fixes for Ruby 1.9 -* Added -m command line option to start a monitor process -* normalize logging in worker -* Deprecate #send_later and #send_at in favor of new #delay method -* Added @#delay@ to Object that allows you to delay any method and pass options: - options = {:priority => 19, :run_at => 5.minutes.from_now} - UserMailer.delay(options).deliver_confirmation(@user) - -2.0.3 - 2010-04-16 -================== -* Fix initialization for Rails 2.x - -2.0.2 - 2010-04-08 -================== -* Fixes to Mongo Mapper backend [ "14be7a24":http://github.com/collectiveidea/delayed_job/commit/14be7a24, "dafd5f46":http://github.com/collectiveidea/delayed_job/commit/dafd5f46, "54d40913":http://github.com/collectiveidea/delayed_job/commit/54d40913 ] -* DataMapper backend performance improvements [ "93833cce":http://github.com/collectiveidea/delayed_job/commit/93833cce, "e9b1573e":http://github.com/collectiveidea/delayed_job/commit/e9b1573e, "37a16d11":http://github.com/collectiveidea/delayed_job/commit/37a16d11, "803f2bfa":http://github.com/collectiveidea/delayed_job/commit/803f2bfa ] -* Fixed Delayed::Command to create tmp/pids directory [ "8ec8ca41":http://github.com/collectiveidea/delayed_job/commit/8ec8ca41 ] -* Railtie to perform Rails 3 initialization [ "3e0fc41f":http://github.com/collectiveidea/delayed_job/commit/3e0fc41f ] -* Added on_permanent_failure hook [ "d2f14cd6":http://github.com/collectiveidea/delayed_job/commit/d2f14cd6 ] - -2.0.1 - 2010-04-03 -================== -* Bug fix for using ActiveRecord backend with daemon [martinbtt] - -2.0.0 - 2010-04-03 -================== -* Multiple backend support (See README for more details) -* Added MongoMapper backend [zbelzer, moneypools] -* Added DataMapper backend [lpetre] -* Reverse priority so the jobs table can be indexed. Lower numbers have higher priority. The default priority is 0, so increase it for jobs that are not important. -* Move most of the heavy lifting from Job to Worker (#work_off, #reschedule, #run, #min_priority, #max_priority, #max_run_time, #max_attempts, #worker_name) [albus522] -* Remove EvaledJob. Implement your own if you need this functionality. -* Only use Time.zone if it is set. Closes #20 -* Fix for last_error recording when destroy_failed_jobs = false, max_attempts = 1 -* Implemented worker name_prefix to maintain dynamic nature of pid detection -* Some Rails 3 compatibility fixes [fredwu] - -1.8.5 - 2010-03-15 -================== -* Set auto_flushing=true on Rails logger to fix logging in production -* Fix error message when trying to send_later on a method that doesn't exist -* Don't use rails_env in capistrano if it's not set. closes #22 -* Delayed job should append to delayed_job.log not overwrite -* Version bump to 1.8.5 -* fixing Time.now to be Time.zone.now if set to honor the app set local TimeZone -* Replaced @Worker::SLEEP@, @Job::MAX_ATTEMPTS@, and @Job::MAX_RUN_TIME@ with class methods that can be overridden. diff --git a/vendor/plugins/delayed_job/CONTRIBUTING.md b/vendor/plugins/delayed_job/CONTRIBUTING.md deleted file mode 100644 index 8e0f531..0000000 --- a/vendor/plugins/delayed_job/CONTRIBUTING.md +++ /dev/null @@ -1,27 +0,0 @@ -How to contribute -================= - -If you find what looks like a bug: - -* Search the "mailing list":http://groups.google.com/group/delayed_job to see - if anyone else had the same issue. -* Check the "GitHub issue tracker":http://github.com/collectiveidea/delayed_job/issues/ - to see if anyone else has reported issue. -* Make sure you are using the latest version of delayed_job - ![Gem Version](https://badge.fury.io/rb/delayed_job.png) -* Make sure you are using the latest backend gem for delayed_job - * Active Record ![Gem Version](https://badge.fury.io/rb/delayed_job_active_record.png) - * Mongoid ![Gem Version](https://badge.fury.io/rb/delayed_job_mongoid.png) -* If you are still having an issue, create an issue including: - * Ruby version - * Gemfile.lock contents or at least major gem versions, such as Rails version - * Steps to reproduce the issue - * Full backtrace for any errors encountered - -If you want to contribute an enhancement or a fix: - -* Fork the project on GitHub. -* Make your changes with tests. -* Commit the changes without making changes to the Rakefile or any other files - that aren't related to your enhancement or fix. -* Send a pull request. diff --git a/vendor/plugins/delayed_job/Gemfile b/vendor/plugins/delayed_job/Gemfile deleted file mode 100644 index 4ac0c53..0000000 --- a/vendor/plugins/delayed_job/Gemfile +++ /dev/null @@ -1,22 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -platforms :ruby do - gem 'sqlite3' -end - -platforms :jruby do - gem 'jruby-openssl' - gem 'activerecord-jdbcsqlite3-adapter' -end - -group :test do - gem 'activerecord', (ENV['RAILS_VERSION'] || ['>= 3.0', '< 4.1']) - gem 'actionmailer', (ENV['RAILS_VERSION'] || ['>= 3.0', '< 4.1']) - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false -end - -gemspec diff --git a/vendor/plugins/delayed_job/LICENSE.md b/vendor/plugins/delayed_job/LICENSE.md deleted file mode 100644 index 759ff02..0000000 --- a/vendor/plugins/delayed_job/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2005 Tobias Lütke - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOa AND -NONINFRINGEMENT. IN NO EVENT SaALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/plugins/delayed_job/README.md b/vendor/plugins/delayed_job/README.md deleted file mode 100644 index 8d2224f..0000000 --- a/vendor/plugins/delayed_job/README.md +++ /dev/null @@ -1,346 +0,0 @@ -Delayed::Job -============ -[![Gem Version](https://badge.fury.io/rb/delayed_job.png)][gem] -[![Build Status](https://secure.travis-ci.org/collectiveidea/delayed_job.png?branch=master)][travis] -[![Dependency Status](https://gemnasium.com/collectiveidea/delayed_job.png?travis)][gemnasium] -[![Code Climate](https://codeclimate.com/github/collectiveidea/delayed_job.png)][codeclimate] -[![Coverage Status](https://coveralls.io/repos/collectiveidea/delayed_job/badge.png?branch=master)][coveralls] - -[gem]: https://rubygems.org/gems/delayed_job -[travis]: http://travis-ci.org/collectiveidea/delayed_job -[gemnasium]: https://gemnasium.com/collectiveidea/delayed_job -[codeclimate]: https://codeclimate.com/github/collectiveidea/delayed_job -[coveralls]: https://coveralls.io/r/collectiveidea/delayed_job - -Delayed::Job (or DJ) encapsulates the common pattern of asynchronously executing -longer tasks in the background. - -It is a direct extraction from Shopify where the job table is responsible for a -multitude of core tasks. Amongst those tasks are: - -* sending massive newsletters -* image resizing -* http downloads -* updating smart collections -* updating solr, our search server, after product changes -* batch imports -* spam checks - -[Follow us on Twitter][twitter] to get updates and notices about new releases. - -[twitter]: https://twitter.com/delayedjob - -Installation -============ -delayed_job 3.0.0 only supports Rails 3.0+. See the [2.0 -branch](https://github.com/collectiveidea/delayed_job/tree/v2.0) for Rails 2. - -delayed_job supports multiple backends for storing the job queue. [See the wiki -for other backends](http://wiki.github.com/collectiveidea/delayed_job/backends). - -If you plan to use delayed_job with Active Record, add `delayed_job_active_record` to your `Gemfile`. - -```ruby -gem 'delayed_job_active_record' -``` - -If you plan to use delayed_job with Mongoid, add `delayed_job_mongoid` to your `Gemfile`. - -```ruby -gem 'delayed_job_mongoid' -``` - -Run `bundle install` to install the backend and delayed_job gems. - -The Active Record backend requires a jobs table. You can create that table by -running the following command: - - rails generate delayed_job:active_record - rake db:migrate - -Rails 4 -======= -If you are using the protected_attributes gem, it must appear before delayed_job in your gemfile. - -Upgrading from 2.x to 3.0.0 on Active Record -============================================ -Delayed Job 3.0.0 introduces a new column to the delayed_jobs table. - -If you're upgrading from Delayed Job 2.x, run the upgrade generator to create a migration to add the column. - - rails generate delayed_job:upgrade - rake db:migrate - -Queuing Jobs -============ -Call `.delay.method(params)` on any object and it will be processed in the background. - -```ruby -# without delayed_job -@user.activate!(@device) - -# with delayed_job -@user.delay.activate!(@device) -``` - -If a method should always be run in the background, you can call -`#handle_asynchronously` after the method declaration: - -```ruby -class Device - def deliver - # long running method - end - handle_asynchronously :deliver -end - -device = Device.new -device.deliver -``` - -handle_asynchronously can take as options anything you can pass to delay. In -addition, the values can be Proc objects allowing call time evaluation of the -value. For some examples: - -```ruby -class LongTasks - def send_mailer - # Some other code - end - handle_asynchronously :send_mailer, :priority => 20 - - def in_the_future - # Some other code - end - # 5.minutes.from_now will be evaluated when in_the_future is called - handle_asynchronously :in_the_future, :run_at => Proc.new { 5.minutes.from_now } - - def self.when_to_run - 2.hours.from_now - end - - def call_a_class_method - # Some other code - end - handle_asynchronously :call_a_class_method, :run_at => Proc.new { when_to_run } - - attr_reader :how_important - - def call_an_instance_method - # Some other code - end - handle_asynchronously :call_an_instance_method, :priority => Proc.new {|i| i.how_important } -end -``` - -If you ever want to call a `handle_asynchronously`'d method without Delayed Job, for instance while debugging something at the console, just add `_without_delay` to the method name. For instance, if your original method was `foo`, then call `foo_without_delay`. - -Rails 3 Mailers -=============== -Due to how mailers are implemented in Rails 3, we had to do a little work around to get delayed_job to work. - -```ruby -# without delayed_job -Notifier.signup(@user).deliver - -# with delayed_job -Notifier.delay.signup(@user) -``` - -Remove the `.deliver` method to make it work. It's not ideal, but it's the best -we could do for now. - -Named Queues -============ -DJ 3 introduces Resque-style named queues while still retaining DJ-style -priority. The goal is to provide a system for grouping tasks to be worked by -separate pools of workers, which may be scaled and controlled individually. - -Jobs can be assigned to a queue by setting the `queue` option: - -```ruby -object.delay(:queue => 'tracking').method - -Delayed::Job.enqueue job, :queue => 'tracking' - -handle_asynchronously :tweet_later, :queue => 'tweets' -``` - -Running Jobs -============ -`script/delayed_job` can be used to manage a background process which will -start working off jobs. - -To do so, add `gem "daemons"` to your `Gemfile` and make sure you've run `rails -generate delayed_job`. - -You can then do the following: - - RAILS_ENV=production script/delayed_job start - RAILS_ENV=production script/delayed_job stop - - # Runs two workers in separate processes. - RAILS_ENV=production script/delayed_job -n 2 start - RAILS_ENV=production script/delayed_job stop - - # Set the --queue or --queues option to work from a particular queue. - RAILS_ENV=production script/delayed_job --queue=tracking start - RAILS_ENV=production script/delayed_job --queues=mailers,tasks start - - # Runs all available jobs and then exits - RAILS_ENV=production script/delayed_job start --exit-on-complete - # or to run in the foreground - RAILS_ENV=production script/delayed_job run --exit-on-complete - -**Rails 4:** *replace script/delayed_job with bin/delayed_job* - -Workers can be running on any computer, as long as they have access to the -database and their clock is in sync. Keep in mind that each worker will check -the database at least every 5 seconds. - -You can also invoke `rake jobs:work` which will start working off jobs. You can -cancel the rake task with `CTRL-C`. - -If you want to just run all available jobs and exit you can use `rake jobs:workoff` - -Work off queues by setting the `QUEUE` or `QUEUES` environment variable. - - QUEUE=tracking rake jobs:work - QUEUES=mailers,tasks rake jobs:work - -Restarting delayed_job -====================== - -The following syntax will restart delayed jobs: - - RAILS_ENV=production script/delayed_job restart - -To restart multiple delayed_job workers: - - RAILS_ENV=production script/delayed_job -n2 restart - -**Rails 4:** *replace script/delayed_job with bin/delayed_job* - - - -Custom Jobs -=========== -Jobs are simple ruby objects with a method called perform. Any object which responds to perform can be stuffed into the jobs table. Job objects are serialized to yaml so that they can later be resurrected by the job runner. - -```ruby -class NewsletterJob < Struct.new(:text, :emails) - def perform - emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) } - end -end - -Delayed::Job.enqueue NewsletterJob.new('lorem ipsum...', Customers.find(:all).collect(&:email)) -``` -To set a per-job max attempts that overrides the Delayed::Worker.max_attempts you can define a max_attempts method on the job -```ruby -class NewsletterJob < Struct.new(:text, :emails) - def perform - emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) } - end - - def max_attempts - return 3 - end -end -```` - - -Hooks -===== -You can define hooks on your job that will be called at different stages in the process: - -```ruby -class ParanoidNewsletterJob < NewsletterJob - def enqueue(job) - record_stat 'newsletter_job/enqueue' - end - - def perform - emails.each { |e| NewsletterMailer.deliver_text_to_email(text, e) } - end - - def before(job) - record_stat 'newsletter_job/start' - end - - def after(job) - record_stat 'newsletter_job/after' - end - - def success(job) - record_stat 'newsletter_job/success' - end - - def error(job, exception) - Airbrake.notify(exception) - end - - def failure(job) - page_sysadmin_in_the_middle_of_the_night - end -end -``` - -Gory Details -============ -The library revolves around a delayed_jobs table which looks as follows: - -```ruby -create_table :delayed_jobs, :force => true do |table| - table.integer :priority, :default => 0 # Allows some jobs to jump to the front of the queue - table.integer :attempts, :default => 0 # Provides for retries, but still fail eventually. - table.text :handler # YAML-encoded string of the object that will do work - table.text :last_error # reason for last failure (See Note below) - table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future. - table.datetime :locked_at # Set when a client is working on this object - table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead) - table.string :locked_by # Who is working on this object (if locked) - table.string :queue # The name of the queue this job is in - table.timestamps -end -``` - -On failure, the job is scheduled again in 5 seconds + N ** 4, where N is the number of retries. - -The default Worker.max_attempts is 25. After this, the job either deleted (default), or left in the database with "failed_at" set. -With the default of 25 attempts, the last retry will be 20 days later, with the last interval being almost 100 hours. - -The default Worker.max_run_time is 4.hours. If your job takes longer than that, another computer could pick it up. It's up to you to -make sure your job doesn't exceed this time. You should set this to the longest time you think the job could take. - -By default, it will delete failed jobs (and it always deletes successful jobs). If you want to keep failed jobs, set -Delayed::Worker.destroy_failed_jobs = false. The failed jobs will be marked with non-null failed_at. - -By default all jobs are scheduled with priority = 0, which is top priority. You can change this by setting Delayed::Worker.default_priority to something else. Lower numbers have higher priority. - -The default behavior is to read 5 jobs from the queue when finding an available job. You can configure this by setting Delayed::Worker.read_ahead. - -By default all jobs will be queued without a named queue. A default named queue can be specified by using Delayed::Worker.default_queue_name. - -It is possible to disable delayed jobs for testing purposes. Set Delayed::Worker.delay_jobs = false to execute all jobs realtime. - -Here is an example of changing job parameters in Rails: - -```ruby -# config/initializers/delayed_job_config.rb -Delayed::Worker.destroy_failed_jobs = false -Delayed::Worker.sleep_delay = 60 -Delayed::Worker.max_attempts = 3 -Delayed::Worker.max_run_time = 5.minutes -Delayed::Worker.read_ahead = 10 -Delayed::Worker.default_queue_name = 'default' -Delayed::Worker.delay_jobs = !Rails.env.test? -``` - -Cleaning up -=========== -You can invoke `rake jobs:clear` to delete all jobs in the queue. - -Mailing List -============ -Join us on the [mailing list](http://groups.google.com/group/delayed_job) diff --git a/vendor/plugins/delayed_job/Rakefile b/vendor/plugins/delayed_job/Rakefile deleted file mode 100644 index 9b760a9..0000000 --- a/vendor/plugins/delayed_job/Rakefile +++ /dev/null @@ -1,11 +0,0 @@ -# -*- encoding: utf-8 -*- -require 'bundler/setup' -Bundler::GemHelper.install_tasks - -require 'rspec/core/rake_task' -desc 'Run the specs' -RSpec::Core::RakeTask.new do |r| - r.verbose = false -end - -task :default => :spec diff --git a/vendor/plugins/delayed_job/benchmarks.rb b/vendor/plugins/delayed_job/benchmarks.rb deleted file mode 100644 index 17bbf9f..0000000 --- a/vendor/plugins/delayed_job/benchmarks.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'spec/helper' -require 'logger' -require 'benchmark' - -# Delayed::Worker.logger = Logger.new('/dev/null') - -Benchmark.bm(10) do |x| - Delayed::Job.delete_all - n = 10000 - n.times { "foo".delay.length } - - x.report { Delayed::Worker.new(:quiet => true).work_off(n) } -end diff --git a/vendor/plugins/delayed_job/contrib/delayed_job.monitrc b/vendor/plugins/delayed_job/contrib/delayed_job.monitrc deleted file mode 100644 index 429c26a..0000000 --- a/vendor/plugins/delayed_job/contrib/delayed_job.monitrc +++ /dev/null @@ -1,14 +0,0 @@ -# an example Monit configuration file for delayed_job -# See: http://stackoverflow.com/questions/1226302/how-to-monitor-delayedjob-with-monit/1285611 -# -# To use: -# 1. copy to /var/www/apps/{app_name}/shared/delayed_job.monitrc -# 2. replace {app_name} as appropriate -# 3. add this to your /etc/monit/monitrc -# -# include /var/www/apps/{app_name}/shared/delayed_job.monitrc - -check process delayed_job - with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.pid - start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job start" - stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job stop" diff --git a/vendor/plugins/delayed_job/contrib/delayed_job_multiple.monitrc b/vendor/plugins/delayed_job/contrib/delayed_job_multiple.monitrc deleted file mode 100644 index 2f63e72..0000000 --- a/vendor/plugins/delayed_job/contrib/delayed_job_multiple.monitrc +++ /dev/null @@ -1,34 +0,0 @@ -# an example Monit configuration file for delayed_job running multiple processes -# -# To use: -# 1. copy to /var/www/apps/{app_name}/shared/delayed_job.monitrc -# 2. replace {app_name} as appropriate -# you might also need to change the program strings to -# "/bin/su - {username} -c '/usr/bin/env ...'" -# to load your shell environment. -# -# 3. add this to your /etc/monit/monitrc -# -# include /var/www/apps/{app_name}/shared/delayed_job.monitrc -# -# The processes are grouped so that monit can act on them as a whole, e.g. -# -# monit -g delayed_job restart - -check process delayed_job_0 - with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.0.pid - start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job start -i 0" - stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job stop -i 0" - group delayed_job - -check process delayed_job_1 - with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.1.pid - start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job start -i 1" - stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job stop -i 1" - group delayed_job - -check process delayed_job_2 - with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.2.pid - start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job start -i 2" - stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/script/delayed_job stop -i 2" - group delayed_job diff --git a/vendor/plugins/delayed_job/contrib/delayed_job_rails_4.monitrc b/vendor/plugins/delayed_job/contrib/delayed_job_rails_4.monitrc deleted file mode 100644 index e0b2a4d..0000000 --- a/vendor/plugins/delayed_job/contrib/delayed_job_rails_4.monitrc +++ /dev/null @@ -1,14 +0,0 @@ -# an example Monit configuration file for delayed_job -# See: http://stackoverflow.com/questions/1226302/how-to-monitor-delayedjob-with-monit/1285611 -# -# To use: -# 1. copy to /var/www/apps/{app_name}/shared/delayed_job.monitrc -# 2. replace {app_name} as appropriate -# 3. add this to your /etc/monit/monitrc -# -# include /var/www/apps/{app_name}/shared/delayed_job.monitrc - -check process delayed_job - with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.pid - start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/bin/delayed_job start" - stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/bin/delayed_job stop" diff --git a/vendor/plugins/delayed_job/contrib/delayed_job_rails_4_multiple.monitrc b/vendor/plugins/delayed_job/contrib/delayed_job_rails_4_multiple.monitrc deleted file mode 100644 index 6db1ca6..0000000 --- a/vendor/plugins/delayed_job/contrib/delayed_job_rails_4_multiple.monitrc +++ /dev/null @@ -1,34 +0,0 @@ -# an example Monit configuration file for delayed_job running multiple processes -# -# To use: -# 1. copy to /var/www/apps/{app_name}/shared/delayed_job.monitrc -# 2. replace {app_name} as appropriate -# you might also need to change the program strings to -# "/bin/su - {username} -c '/usr/bin/env ...'" -# to load your shell environment. -# -# 3. add this to your /etc/monit/monitrc -# -# include /var/www/apps/{app_name}/shared/delayed_job.monitrc -# -# The processes are grouped so that monit can act on them as a whole, e.g. -# -# monit -g delayed_job restart - -check process delayed_job_0 - with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.0.pid - start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/bin/delayed_job start -i 0" - stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/bin/delayed_job stop -i 0" - group delayed_job - -check process delayed_job_1 - with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.1.pid - start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/bin/delayed_job start -i 1" - stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/bin/delayed_job stop -i 1" - group delayed_job - -check process delayed_job_2 - with pidfile /var/www/apps/{app_name}/shared/pids/delayed_job.2.pid - start program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/bin/delayed_job start -i 2" - stop program = "/usr/bin/env RAILS_ENV=production /var/www/apps/{app_name}/current/bin/delayed_job stop -i 2" - group delayed_job diff --git a/vendor/plugins/delayed_job/delayed_job.gemspec b/vendor/plugins/delayed_job/delayed_job.gemspec deleted file mode 100644 index 8faccb4..0000000 --- a/vendor/plugins/delayed_job/delayed_job.gemspec +++ /dev/null @@ -1,17 +0,0 @@ -# -*- encoding: utf-8 -*- - -Gem::Specification.new do |spec| - spec.add_dependency 'activesupport', ['>= 3.0', '< 4.1'] - spec.authors = ["Brandon Keepers", "Brian Ryckbost", "Chris Gaffney", "David Genord II", "Erik Michaels-Ober", "Matt Griffin", "Steve Richert", "Tobias Lütke"] - spec.description = "Delayed_job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background. It is a direct extraction from Shopify where the job table is responsible for a multitude of core tasks." - spec.email = ['brian@collectiveidea.com'] - spec.files = %w(CHANGELOG.md CONTRIBUTING.md LICENSE.md README.md Rakefile delayed_job.gemspec) - spec.files += Dir.glob('{contrib,lib,recipes,spec}/**/*') - spec.homepage = 'http://github.com/collectiveidea/delayed_job' - spec.licenses = ['MIT'] - spec.name = 'delayed_job' - spec.require_paths = ['lib'] - spec.summary = 'Database-backed asynchronous priority queue system -- Extracted from Shopify' - spec.test_files = Dir.glob('spec/**/*') - spec.version = '4.0.0' -end diff --git a/vendor/plugins/delayed_job/lib/delayed/backend/base.rb b/vendor/plugins/delayed_job/lib/delayed/backend/base.rb deleted file mode 100644 index ea48272..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/backend/base.rb +++ /dev/null @@ -1,156 +0,0 @@ -module Delayed - module Backend - module Base - def self.included(base) - base.extend ClassMethods - end - - module ClassMethods - # Add a job to the queue - def enqueue(*args) - options = { - :priority => Delayed::Worker.default_priority, - :queue => Delayed::Worker.default_queue_name - }.merge!(args.extract_options!) - - options[:payload_object] ||= args.shift - - if args.size > 0 - warn "[DEPRECATION] Passing multiple arguments to `#enqueue` is deprecated. Pass a hash with :priority and :run_at." - options[:priority] = args.first || options[:priority] - options[:run_at] = args[1] - end - - unless options[:payload_object].respond_to?(:perform) - raise ArgumentError, 'Cannot enqueue items which do not respond to perform' - end - - if Delayed::Worker.delay_jobs - self.new(options).tap do |job| - Delayed::Worker.lifecycle.run_callbacks(:enqueue, job) do - job.hook(:enqueue) - job.save - end - end - else - Delayed::Job.new(:payload_object => options[:payload_object]).tap do |job| - job.invoke_job - end - end - end - - def reserve(worker, max_run_time = Worker.max_run_time) - # We get up to 5 jobs from the db. In case we cannot get exclusive access to a job we try the next. - # this leads to a more even distribution of jobs across the worker processes - find_available(worker.name, worker.read_ahead, max_run_time).detect do |job| - job.lock_exclusively!(max_run_time, worker.name) - end - end - - # Allow the backend to attempt recovery from reserve errors - def recover_from(error) - end - - # Hook method that is called before a new worker is forked - def before_fork - end - - # Hook method that is called after a new worker is forked - def after_fork - end - - def work_off(num = 100) - warn "[DEPRECATION] `Delayed::Job.work_off` is deprecated. Use `Delayed::Worker.new.work_off instead." - Delayed::Worker.new.work_off(num) - end - end - - def failed? - !!failed_at - end - alias_method :failed, :failed? - - ParseObjectFromYaml = /\!ruby\/\w+\:([^\s]+)/ - - def name - obj = payload_object - @name ||= obj.respond_to?(:display_name) ? obj.display_name : obj.class.name - rescue DeserializationError - ParseObjectFromYaml.match(handler)[1] - end - - def payload_object=(object) - @payload_object = object - self.handler = object.to_yaml - end - - def payload_object - if YAML.respond_to?(:unsafe_load) - #See https://github.com/dtao/safe_yaml - #When the method is there, we need to load our YAML like this... - @payload_object ||= YAML.load(self.handler, :safe => false) - else - @payload_object ||= YAML.load(self.handler) - end - rescue TypeError, LoadError, NameError, ArgumentError => e - raise DeserializationError, - "Job failed to load: #{e.message}. Handler: #{handler.inspect}" - end - - def invoke_job - Delayed::Worker.lifecycle.run_callbacks(:invoke_job, self) do - begin - hook :before - payload_object.perform - hook :success - rescue Exception => e - hook :error, e - raise e - ensure - hook :after - end - end - end - - # Unlock this job (note: not saved to DB) - def unlock - self.locked_at = nil - self.locked_by = nil - end - - def hook(name, *args) - if payload_object.respond_to?(name) - method = payload_object.method(name) - method.arity == 0 ? method.call : method.call(self, *args) - end - rescue DeserializationError - # do nothing - end - - def reschedule_at - payload_object.respond_to?(:reschedule_at) ? - payload_object.reschedule_at(self.class.db_time_now, attempts) : - self.class.db_time_now + (attempts ** 4) + 5 - end - - def max_attempts - payload_object.max_attempts if payload_object.respond_to?(:max_attempts) - end - - def fail! - update_attributes(:failed_at => self.class.db_time_now) - end - - protected - - def set_default_run_at - self.run_at ||= self.class.db_time_now - end - - # Call during reload operation to clear out internal state - def reset - @payload_object = nil - end - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/backend/shared_spec.rb b/vendor/plugins/delayed_job/lib/delayed/backend/shared_spec.rb deleted file mode 100644 index 1cd847b..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/backend/shared_spec.rb +++ /dev/null @@ -1,594 +0,0 @@ -require File.expand_path('../../../../spec/sample_jobs', __FILE__) - -require 'active_support/core_ext' - -shared_examples_for "a delayed_job backend" do - let(:worker) { Delayed::Worker.new } - - def create_job(opts = {}) - described_class.create(opts.merge(:payload_object => SimpleJob.new)) - end - - before do - Delayed::Worker.max_priority = nil - Delayed::Worker.min_priority = nil - Delayed::Worker.default_priority = 99 - Delayed::Worker.delay_jobs = true - SimpleJob.runs = 0 - described_class.delete_all - end - - after do - Delayed::Worker.reset - end - - it "sets run_at automatically if not set" do - expect(described_class.create(:payload_object => ErrorJob.new ).run_at).not_to be_nil - end - - it "does not set run_at automatically if already set" do - later = described_class.db_time_now + 5.minutes - job = described_class.create(:payload_object => ErrorJob.new, :run_at => later) - expect(job.run_at).to be_within(1).of(later) - end - - describe "#reload" do - it "reloads the payload" do - job = described_class.enqueue :payload_object => SimpleJob.new - expect(job.payload_object.object_id).not_to eq(job.reload.payload_object.object_id) - end - end - - describe "enqueue" do - context "with a hash" do - it "raises ArgumentError when handler doesn't respond_to :perform" do - expect{described_class.enqueue(:payload_object => Object.new)}.to raise_error(ArgumentError) - end - - it "is able to set priority" do - job = described_class.enqueue :payload_object => SimpleJob.new, :priority => 5 - expect(job.priority).to eq(5) - end - - it "uses default priority" do - job = described_class.enqueue :payload_object => SimpleJob.new - expect(job.priority).to eq(99) - end - - it "is able to set run_at" do - later = described_class.db_time_now + 5.minutes - job = described_class.enqueue :payload_object => SimpleJob.new, :run_at => later - expect(job.run_at).to be_within(1).of(later) - end - - it "is able to set queue" do - job = described_class.enqueue :payload_object => SimpleJob.new, :queue => 'tracking' - expect(job.queue).to eq('tracking') - end - end - - context "with multiple arguments" do - it "raises ArgumentError when handler doesn't respond_to :perform" do - expect{described_class.enqueue(Object.new)}.to raise_error(ArgumentError) - end - - it "increases count after enqueuing items" do - described_class.enqueue SimpleJob.new - expect(described_class.count).to eq(1) - end - - it "is able to set priority [DEPRECATED]" do - silence_warnings do - job = described_class.enqueue SimpleJob.new, 5 - expect(job.priority).to eq(5) - end - end - - it "uses default priority when it is not set" do - @job = described_class.enqueue SimpleJob.new - expect(@job.priority).to eq(99) - end - - it "is able to set run_at [DEPRECATED]" do - silence_warnings do - later = described_class.db_time_now + 5.minutes - @job = described_class.enqueue SimpleJob.new, 5, later - expect(@job.run_at).to be_within(1).of(later) - end - end - - it "works with jobs in modules" do - M::ModuleJob.runs = 0 - job = described_class.enqueue M::ModuleJob.new - expect{job.invoke_job}.to change { M::ModuleJob.runs }.from(0).to(1) - end - end - - context "with delay_jobs = false" do - before(:each) do - Delayed::Worker.delay_jobs = false - end - - it "does not increase count after enqueuing items" do - described_class.enqueue SimpleJob.new - expect(described_class.count).to eq(0) - end - - it "invokes the enqueued job" do - job = SimpleJob.new - job.should_receive(:perform) - described_class.enqueue job - end - - it "returns a job, not the result of invocation" do - expect(described_class.enqueue(SimpleJob.new)).to be_instance_of(described_class) - end - end - end - - describe "callbacks" do - before(:each) do - CallbackJob.messages = [] - end - - %w(before success after).each do |callback| - it "calls #{callback} with job" do - job = described_class.enqueue(CallbackJob.new) - job.payload_object.should_receive(callback).with(job) - job.invoke_job - end - end - - it "calls before and after callbacks" do - job = described_class.enqueue(CallbackJob.new) - expect(CallbackJob.messages).to eq(["enqueue"]) - job.invoke_job - expect(CallbackJob.messages).to eq(["enqueue", "before", "perform", "success", "after"]) - end - - it "calls the after callback with an error" do - job = described_class.enqueue(CallbackJob.new) - job.payload_object.should_receive(:perform).and_raise(RuntimeError.new("fail")) - - expect{job.invoke_job}.to raise_error - expect(CallbackJob.messages).to eq(["enqueue", "before", "error: RuntimeError", "after"]) - end - - it "calls error when before raises an error" do - job = described_class.enqueue(CallbackJob.new) - job.payload_object.should_receive(:before).and_raise(RuntimeError.new("fail")) - expect{job.invoke_job}.to raise_error(RuntimeError) - expect(CallbackJob.messages).to eq(["enqueue", "error: RuntimeError", "after"]) - end - end - - describe "payload_object" do - it "raises a DeserializationError when the job class is totally unknown" do - job = described_class.new :handler => "--- !ruby/object:JobThatDoesNotExist {}" - expect{job.payload_object}.to raise_error(Delayed::DeserializationError) - end - - it "raises a DeserializationError when the job struct is totally unknown" do - job = described_class.new :handler => "--- !ruby/struct:StructThatDoesNotExist {}" - expect{job.payload_object}.to raise_error(Delayed::DeserializationError) - end - - it "raises a DeserializationError when the YAML.load raises argument error" do - job = described_class.new :handler => "--- !ruby/struct:GoingToRaiseArgError {}" - YAML.should_receive(:load).and_raise(ArgumentError) - expect{job.payload_object}.to raise_error(Delayed::DeserializationError) - end - end - - describe "reserve" do - before do - Delayed::Worker.max_run_time = 2.minutes - end - - after do - Time.zone = nil - end - - it "does not reserve failed jobs" do - create_job :attempts => 50, :failed_at => described_class.db_time_now - expect(described_class.reserve(worker)).to be_nil - end - - it "does not reserve jobs scheduled for the future" do - create_job :run_at => described_class.db_time_now + 1.minute - expect(described_class.reserve(worker)).to be_nil - end - - it "reserves jobs scheduled for the past" do - job = create_job :run_at => described_class.db_time_now - 1.minute - expect(described_class.reserve(worker)).to eq(job) - end - - it "reserves jobs scheduled for the past when time zones are involved" do - Time.zone = 'US/Eastern' - job = create_job :run_at => described_class.db_time_now - 1.minute - expect(described_class.reserve(worker)).to eq(job) - end - - it "does not reserve jobs locked by other workers" do - job = create_job - other_worker = Delayed::Worker.new - other_worker.name = 'other_worker' - expect(described_class.reserve(other_worker)).to eq(job) - expect(described_class.reserve(worker)).to be_nil - end - - it "reserves open jobs" do - job = create_job - expect(described_class.reserve(worker)).to eq(job) - end - - it "reserves expired jobs" do - job = create_job(:locked_by => 'some other worker', :locked_at => described_class.db_time_now - Delayed::Worker.max_run_time - 1.minute) - expect(described_class.reserve(worker)).to eq(job) - end - - it "reserves own jobs" do - job = create_job(:locked_by => worker.name, :locked_at => (described_class.db_time_now - 1.minutes)) - expect(described_class.reserve(worker)).to eq(job) - end - end - - context "#name" do - it "is the class name of the job that was enqueued" do - expect(described_class.create(:payload_object => ErrorJob.new ).name).to eq('ErrorJob') - end - - it "is the method that will be called if its a performable method object" do - job = described_class.new(:payload_object => NamedJob.new) - expect(job.name).to eq('named_job') - end - - it "is the instance method that will be called if its a performable method object" do - job = Story.create(:text => "...").delay.save - expect(job.name).to eq('Story#save') - end - - it "parses from handler on deserialization error" do - job = Story.create(:text => "...").delay.text - job.payload_object.object.destroy - expect(job.reload.name).to eq('Delayed::PerformableMethod') - end - end - - context "worker prioritization" do - after do - Delayed::Worker.max_priority = nil - Delayed::Worker.min_priority = nil - end - - it "fetches jobs ordered by priority" do - 10.times { described_class.enqueue SimpleJob.new, :priority => rand(10) } - jobs = [] - 10.times { jobs << described_class.reserve(worker) } - expect(jobs.size).to eq(10) - jobs.each_cons(2) do |a, b| - expect(a.priority).to be <= b.priority - end - end - - it "only finds jobs greater than or equal to min priority" do - min = 5 - Delayed::Worker.min_priority = min - [4,5,6].sort_by {|i| rand }.each {|i| create_job :priority => i } - 2.times do - job = described_class.reserve(worker) - expect(job.priority).to be >= min - job.destroy - end - expect(described_class.reserve(worker)).to be_nil - end - - it "only finds jobs less than or equal to max priority" do - max = 5 - Delayed::Worker.max_priority = max - [4,5,6].sort_by {|i| rand }.each {|i| create_job :priority => i } - 2.times do - job = described_class.reserve(worker) - expect(job.priority).to be <= max - job.destroy - end - expect(described_class.reserve(worker)).to be_nil - end - end - - context "clear_locks!" do - before do - @job = create_job(:locked_by => 'worker1', :locked_at => described_class.db_time_now) - end - - it "clears locks for the given worker" do - described_class.clear_locks!('worker1') - expect(described_class.reserve(worker)).to eq(@job) - end - - it "does not clear locks for other workers" do - described_class.clear_locks!('different_worker') - expect(described_class.reserve(worker)).not_to eq(@job) - end - end - - context "unlock" do - before do - @job = create_job(:locked_by => 'worker', :locked_at => described_class.db_time_now) - end - - it "clears locks" do - @job.unlock - expect(@job.locked_by).to be_nil - expect(@job.locked_at).to be_nil - end - end - - context "large handler" do - before do - text = "Lorem ipsum dolor sit amet. " * 1000 - @job = described_class.enqueue Delayed::PerformableMethod.new(text, :length, {}) - end - - it "has an id" do - expect(@job.id).not_to be_nil - end - end - - context "named queues" do - context "when worker has one queue set" do - before(:each) do - worker.queues = ['large'] - end - - it "only works off jobs which are from its queue" do - expect(SimpleJob.runs).to eq(0) - - create_job(:queue => "large") - create_job(:queue => "small") - worker.work_off - - expect(SimpleJob.runs).to eq(1) - end - end - - context "when worker has two queue set" do - before(:each) do - worker.queues = ['large', 'small'] - end - - it "only works off jobs which are from its queue" do - expect(SimpleJob.runs).to eq(0) - - create_job(:queue => "large") - create_job(:queue => "small") - create_job(:queue => "medium") - create_job - worker.work_off - - expect(SimpleJob.runs).to eq(2) - end - end - - context "when worker does not have queue set" do - before(:each) do - worker.queues = [] - end - - it "works off all jobs" do - expect(SimpleJob.runs).to eq(0) - - create_job(:queue => "one") - create_job(:queue => "two") - create_job - worker.work_off - - expect(SimpleJob.runs).to eq(3) - end - end - end - - context "max_attempts" do - before(:each) do - @job = described_class.enqueue SimpleJob.new - end - - it "is not defined" do - expect(@job.max_attempts).to be_nil - end - - it "uses the max_retries value on the payload when defined" do - @job.payload_object.stub(:max_attempts).and_return(99) - expect(@job.max_attempts).to eq(99) - end - end - - describe "yaml serialization" do - it "reloads changed attributes" do - story = Story.create(:text => 'hello') - job = story.delay.tell - story.update_attributes :text => 'goodbye' - expect(job.reload.payload_object.object.text).to eq('goodbye') - end - - it "raises error ArgumentError the record is not persisted" do - story = Story.new(:text => 'hello') - if story.respond_to?(:new_record?) - expect { - story.delay.tell - }.to raise_error(ArgumentError, "Jobs cannot be created for records before they've been persisted") - end - end - - it "raises deserialization error for destroyed records" do - story = Story.create(:text => 'hello') - job = story.delay.tell - story.destroy - expect { - job.reload.payload_object - }.to raise_error(Delayed::DeserializationError) - end - end - - describe "worker integration" do - before do - Delayed::Job.delete_all - SimpleJob.runs = 0 - end - - describe "running a job" do - it "fails after Worker.max_run_time" do - Delayed::Worker.max_run_time = 1.second - job = Delayed::Job.create :payload_object => LongRunningJob.new - worker.run(job) - expect(job.reload.last_error).to match(/expired/) - expect(job.reload.last_error).to match(/Delayed::Worker.max_run_time is only 1 second/) - expect(job.attempts).to eq(1) - end - - context "when the job raises a deserialization error" do - after do - Delayed::Worker.destroy_failed_jobs = true - end - - it "marks the job as failed" do - Delayed::Worker.destroy_failed_jobs = false - job = described_class.create! :handler => "--- !ruby/object:JobThatDoesNotExist {}" - worker.work_off - job.reload - expect(job).to be_failed - end - end - end - - describe "failed jobs" do - before do - @job = Delayed::Job.enqueue(ErrorJob.new, :run_at => described_class.db_time_now - 1) - end - - after do - # reset default - Delayed::Worker.destroy_failed_jobs = true - end - - it "records last_error when destroy_failed_jobs = false, max_attempts = 1" do - Delayed::Worker.destroy_failed_jobs = false - Delayed::Worker.max_attempts = 1 - worker.run(@job) - @job.reload - expect(@job.last_error).to match(/did not work/) - expect(@job.attempts).to eq(1) - expect(@job).to be_failed - end - - it "re-schedules jobs after failing" do - worker.work_off - @job.reload - expect(@job.last_error).to match(/did not work/) - expect(@job.last_error).to match(/sample_jobs.rb:\d+:in `perform'/) - expect(@job.attempts).to eq(1) - expect(@job.run_at).to be > Delayed::Job.db_time_now - 10.minutes - expect(@job.run_at).to be < Delayed::Job.db_time_now + 10.minutes - expect(@job.locked_by).to be_nil - expect(@job.locked_at).to be_nil - end - - it "re-schedules jobs with handler provided time if present" do - job = Delayed::Job.enqueue(CustomRescheduleJob.new(99.minutes)) - worker.run(job) - job.reload - - expect((Delayed::Job.db_time_now + 99.minutes - job.run_at).abs).to be < 1 - end - - it "does not fail when the triggered error doesn't have a message" do - error_with_nil_message = StandardError.new - error_with_nil_message.stub(:message).and_return nil - @job.stub(:invoke_job).and_raise error_with_nil_message - expect{worker.run(@job)}.not_to raise_error - end - end - - context "reschedule" do - before do - @job = Delayed::Job.create :payload_object => SimpleJob.new - end - - share_examples_for "any failure more than Worker.max_attempts times" do - context "when the job's payload has a #failure hook" do - before do - @job = Delayed::Job.create :payload_object => OnPermanentFailureJob.new - expect(@job.payload_object).to respond_to :failure - end - - it "runs that hook" do - @job.payload_object.should_receive :failure - worker.reschedule(@job) - end - end - - context "when the job's payload has no #failure hook" do - # It's a little tricky to test this in a straightforward way, - # because putting a should_not_receive expectation on - # @job.payload_object.failure makes that object - # incorrectly return true to - # payload_object.respond_to? :failure, which is what - # reschedule uses to decide whether to call failure. - # So instead, we just make sure that the payload_object as it - # already stands doesn't respond_to? failure, then - # shove it through the iterated reschedule loop and make sure we - # don't get a NoMethodError (caused by calling that nonexistent - # failure method). - - before do - expect(@job.payload_object).not_to respond_to(:failure) - end - - it "does not try to run that hook" do - expect { - Delayed::Worker.max_attempts.times { worker.reschedule(@job) } - }.not_to raise_exception - end - end - end - - context "and we want to destroy jobs" do - it_should_behave_like "any failure more than Worker.max_attempts times" - - it "is destroyed if it failed more than Worker.max_attempts times" do - @job.should_receive(:destroy) - Delayed::Worker.max_attempts.times { worker.reschedule(@job) } - end - - it "is not destroyed if failed fewer than Worker.max_attempts times" do - @job.should_not_receive(:destroy) - (Delayed::Worker.max_attempts - 1).times { worker.reschedule(@job) } - end - end - - context "and we don't want to destroy jobs" do - before do - Delayed::Worker.destroy_failed_jobs = false - end - - after do - Delayed::Worker.destroy_failed_jobs = true - end - - it_should_behave_like "any failure more than Worker.max_attempts times" - - it "is failed if it failed more than Worker.max_attempts times" do - expect(@job.reload).not_to be_failed - Delayed::Worker.max_attempts.times { worker.reschedule(@job) } - expect(@job.reload).to be_failed - end - - it "is not failed if it failed fewer than Worker.max_attempts times" do - (Delayed::Worker.max_attempts - 1).times { worker.reschedule(@job) } - expect(@job.reload).not_to be_failed - end - end - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/command.rb b/vendor/plugins/delayed_job/lib/delayed/command.rb deleted file mode 100644 index 102bbdd..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/command.rb +++ /dev/null @@ -1,111 +0,0 @@ -begin - require 'daemons' -rescue LoadError - raise "You need to add gem 'daemons' to your Gemfile if you wish to use it." -end -require 'optparse' - -module Delayed - class Command - attr_accessor :worker_count - - def initialize(args) - @options = { - :quiet => true, - :pid_dir => "#{Rails.root}/tmp/pids" - } - - @worker_count = 1 - @monitor = false - - opts = OptionParser.new do |opts| - opts.banner = "Usage: #{File.basename($0)} [options] start|stop|restart|run" - - opts.on('-h', '--help', 'Show this message') do - puts opts - exit 1 - end - opts.on('-e', '--environment=NAME', 'Specifies the environment to run this delayed jobs under (test/development/production).') do |e| - STDERR.puts "The -e/--environment option has been deprecated and has no effect. Use RAILS_ENV and see http://github.com/collectiveidea/delayed_job/issues/#issue/7" - end - opts.on('--min-priority N', 'Minimum priority of jobs to run.') do |n| - @options[:min_priority] = n - end - opts.on('--max-priority N', 'Maximum priority of jobs to run.') do |n| - @options[:max_priority] = n - end - opts.on('-n', '--number_of_workers=workers', "Number of unique workers to spawn") do |worker_count| - @worker_count = worker_count.to_i rescue 1 - end - opts.on('--pid-dir=DIR', 'Specifies an alternate directory in which to store the process ids.') do |dir| - @options[:pid_dir] = dir - end - opts.on('-i', '--identifier=n', 'A numeric identifier for the worker.') do |n| - @options[:identifier] = n - end - opts.on('-m', '--monitor', 'Start monitor process.') do - @monitor = true - end - opts.on('--sleep-delay N', "Amount of time to sleep when no jobs are found") do |n| - @options[:sleep_delay] = n.to_i - end - opts.on('--read-ahead N', "Number of jobs from the queue to consider") do |n| - @options[:read_ahead] = n - end - opts.on('-p', '--prefix NAME', "String to be prefixed to worker process names") do |prefix| - @options[:prefix] = prefix - end - opts.on('--queues=queues', "Specify which queue DJ must look up for jobs") do |queues| - @options[:queues] = queues.split(',') - end - opts.on('--queue=queue', "Specify which queue DJ must look up for jobs") do |queue| - @options[:queues] = queue.split(',') - end - opts.on('--exit-on-complete', "Exit when no more jobs are available to run. This will exit if all jobs are scheduled to run in the future.") do - @options[:exit_on_complete] = true - end - end - @args = opts.parse!(args) - end - - def daemonize - dir = @options[:pid_dir] - Dir.mkdir(dir) unless File.exists?(dir) - - if @worker_count > 1 && @options[:identifier] - raise ArgumentError, 'Cannot specify both --number-of-workers and --identifier' - elsif @worker_count == 1 && @options[:identifier] - process_name = "delayed_job.#{@options[:identifier]}" - run_process(process_name, dir) - else - worker_count.times do |worker_index| - process_name = worker_count == 1 ? "delayed_job" : "delayed_job.#{worker_index}" - run_process(process_name, dir) - end - end - end - - def run_process(process_name, dir) - Delayed::Worker.before_fork - Daemons.run_proc(process_name, :dir => dir, :dir_mode => :normal, :monitor => @monitor, :ARGV => @args) do |*args| - $0 = File.join(@options[:prefix], process_name) if @options[:prefix] - run process_name - end - end - - def run(worker_name = nil) - Dir.chdir(Rails.root) - - Delayed::Worker.after_fork - Delayed::Worker.logger = Logger.new(File.join(Rails.root, 'log', "#{Rails.env}_delayed_job.log")) - - worker = Delayed::Worker.new(@options) - worker.name_prefix = "#{worker_name} " - worker.start - rescue => e - Rails.logger.fatal e - STDERR.puts e.message - exit 1 - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/compatibility.rb b/vendor/plugins/delayed_job/lib/delayed/compatibility.rb deleted file mode 100644 index 72778f9..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/compatibility.rb +++ /dev/null @@ -1,27 +0,0 @@ -require 'active_support/version' - -module Delayed - module Compatibility - if ActiveSupport::VERSION::MAJOR >= 4 - require 'active_support/proxy_object' - - def self.executable_prefix - 'bin' - end - - def self.proxy_object_class - ActiveSupport::ProxyObject - end - else - require 'active_support/basic_object' - - def self.executable_prefix - 'script' - end - - def self.proxy_object_class - ActiveSupport::BasicObject - end - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/deserialization_error.rb b/vendor/plugins/delayed_job/lib/delayed/deserialization_error.rb deleted file mode 100644 index 960d8f5..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/deserialization_error.rb +++ /dev/null @@ -1,4 +0,0 @@ -module Delayed - class DeserializationError < StandardError - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/exceptions.rb b/vendor/plugins/delayed_job/lib/delayed/exceptions.rb deleted file mode 100644 index e3fbf6e..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/exceptions.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'timeout' - -module Delayed - class WorkerTimeout < Timeout::Error - def message - "#{super} (Delayed::Worker.max_run_time is only #{Delayed::Worker.max_run_time.to_i} seconds)" - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/lifecycle.rb b/vendor/plugins/delayed_job/lib/delayed/lifecycle.rb deleted file mode 100644 index 507ba11..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/lifecycle.rb +++ /dev/null @@ -1,84 +0,0 @@ -module Delayed - class InvalidCallback < Exception; end - - class Lifecycle - EVENTS = { - :enqueue => [:job], - :execute => [:worker], - :loop => [:worker], - :perform => [:worker, :job], - :error => [:worker, :job], - :failure => [:worker, :job], - :invoke_job => [:job] - } - - def initialize - @callbacks = EVENTS.keys.inject({}) { |hash, e| hash[e] = Callback.new; hash } - end - - def before(event, &block) - add(:before, event, &block) - end - - def after(event, &block) - add(:after, event, &block) - end - - def around(event, &block) - add(:around, event, &block) - end - - def run_callbacks(event, *args, &block) - missing_callback(event) unless @callbacks.has_key?(event) - - unless EVENTS[event].size == args.size - raise ArgumentError, "Callback #{event} expects #{EVENTS[event].size} parameter(s): #{EVENTS[event].join(', ')}" - end - - @callbacks[event].execute(*args, &block) - end - - private - - def add(type, event, &block) - missing_callback(event) unless @callbacks.has_key?(event) - - @callbacks[event].add(type, &block) - end - - def missing_callback(event) - raise InvalidCallback, "Unknown callback event: #{event}" - end - end - - class Callback - def initialize - @before = [] - @after = [] - - # Identity proc. Avoids special cases when there is no existing around chain. - @around = lambda { |*args, &block| block.call(*args) } - end - - def execute(*args, &block) - @before.each { |c| c.call(*args) } - result = @around.call(*args, &block) - @after.each { |c| c.call(*args) } - result - end - - def add(type, &callback) - case type - when :before - @before << callback - when :after - @after << callback - when :around - chain = @around # use a local variable so that the current chain is closed over in the following lambda - @around = lambda { |*a, &block| chain.call(*a) { |*b| callback.call(*b, &block) } } - else - raise InvalidCallback, "Invalid callback type: #{type}" - end - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/message_sending.rb b/vendor/plugins/delayed_job/lib/delayed/message_sending.rb deleted file mode 100644 index e8af95a..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/message_sending.rb +++ /dev/null @@ -1,53 +0,0 @@ -require 'active_support/core_ext/module/aliasing' - -module Delayed - class DelayProxy < Delayed::Compatibility.proxy_object_class - def initialize(payload_class, target, options) - @payload_class = payload_class - @target = target - @options = options - end - - def method_missing(method, *args) - Job.enqueue({:payload_object => @payload_class.new(@target, method.to_sym, args)}.merge(@options)) - end - end - - module MessageSending - def delay(options = {}) - DelayProxy.new(PerformableMethod, self, options) - end - alias __delay__ delay - - def send_later(method, *args) - warn "[DEPRECATION] `object.send_later(:method)` is deprecated. Use `object.delay.method" - __delay__.__send__(method, *args) - end - - def send_at(time, method, *args) - warn "[DEPRECATION] `object.send_at(time, :method)` is deprecated. Use `object.delay(:run_at => time).method" - __delay__(:run_at => time).__send__(method, *args) - end - - module ClassMethods - def handle_asynchronously(method, opts = {}) - aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1 - with_method, without_method = "#{aliased_method}_with_delay#{punctuation}", "#{aliased_method}_without_delay#{punctuation}" - define_method(with_method) do |*args| - curr_opts = opts.clone - curr_opts.each_key do |key| - if (val = curr_opts[key]).is_a?(Proc) - curr_opts[key] = if val.arity == 1 - val.call(self) - else - val.call - end - end - end - delay(curr_opts).__send__(without_method, *args) - end - alias_method_chain method, :delay - end - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/performable_mailer.rb b/vendor/plugins/delayed_job/lib/delayed/performable_mailer.rb deleted file mode 100644 index f3a898e..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/performable_mailer.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'mail' - -module Delayed - class PerformableMailer < PerformableMethod - def perform - object.send(method_name, *args).deliver - end - end - - module DelayMail - def delay(options = {}) - DelayProxy.new(PerformableMailer, self, options) - end - end -end - -Mail::Message.class_eval do - def delay(*args) - raise RuntimeError, "Use MyMailer.delay.mailer_action(args) to delay sending of emails." - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/performable_method.rb b/vendor/plugins/delayed_job/lib/delayed/performable_method.rb deleted file mode 100644 index 40aaf68..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/performable_method.rb +++ /dev/null @@ -1,37 +0,0 @@ -require 'active_support/core_ext/module/delegation' - -module Delayed - class PerformableMethod - attr_accessor :object, :method_name, :args - - delegate :method, :to => :object - - def initialize(object, method_name, args) - raise NoMethodError, "undefined method `#{method_name}' for #{object.inspect}" unless object.respond_to?(method_name, true) - - if object.respond_to?(:new_record?) && object.new_record? - raise(ArgumentError, 'Jobs cannot be created for records before they\'ve been persisted') - end - - self.object = object - self.args = args - self.method_name = method_name.to_sym - end - - def display_name - "#{object.class}##{method_name}" - end - - def perform - object.send(method_name, *args) if object - end - - def method_missing(symbol, *args) - object.send(symbol, *args) - end - - def respond_to?(symbol, include_private=false) - super || object.respond_to?(symbol, include_private) - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/plugin.rb b/vendor/plugins/delayed_job/lib/delayed/plugin.rb deleted file mode 100644 index 18f2c62..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/plugin.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'active_support/core_ext/class/attribute' - -module Delayed - class Plugin - class_attribute :callback_block - - def self.callbacks(&block) - self.callback_block = block - end - - def initialize - self.class.callback_block.call(Delayed::Worker.lifecycle) if self.class.callback_block - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/plugins/clear_locks.rb b/vendor/plugins/delayed_job/lib/delayed/plugins/clear_locks.rb deleted file mode 100644 index 05224a0..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/plugins/clear_locks.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Delayed - module Plugins - class ClearLocks < Plugin - callbacks do |lifecycle| - lifecycle.around(:execute) do |worker, &block| - begin - block.call(worker) - ensure - Delayed::Job.clear_locks!(worker.name) - end - end - end - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/psych_ext.rb b/vendor/plugins/delayed_job/lib/delayed/psych_ext.rb deleted file mode 100644 index 827a685..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/psych_ext.rb +++ /dev/null @@ -1,146 +0,0 @@ -if defined?(ActiveRecord) - ActiveRecord::Base.class_eval do - if instance_methods.include?(:encode_with) - def encode_with_override(coder) - encode_with_without_override(coder) - coder.tag = "!ruby/ActiveRecord:#{self.class.name}" - end - alias_method :encode_with_without_override, :encode_with - alias_method :encode_with, :encode_with_override - else - def encode_with(coder) - coder["attributes"] = attributes - coder.tag = "!ruby/ActiveRecord:#{self.class.name}" - end - end - end -end - -class Delayed::PerformableMethod - # serialize to YAML - def encode_with(coder) - coder.map = { - "object" => object, - "method_name" => method_name, - "args" => args - } - end -end - -module Psych - module Visitors - class YAMLTree - def visit_Class(klass) - @emitter.scalar klass.name, nil, '!ruby/class', false, false, Nodes::Scalar::SINGLE_QUOTED - end - end - - class ToRuby - def visit_Psych_Nodes_Scalar(o) - @st[o.anchor] = o.value if o.anchor - - if klass = Psych.load_tags[o.tag] - instance = klass.allocate - - if instance.respond_to?(:init_with) - coder = Psych::Coder.new(o.tag) - coder.scalar = o.value - instance.init_with coder - end - - return instance - end - - return o.value if o.quoted - return @ss.tokenize(o.value) unless o.tag - - case o.tag - when '!binary', 'tag:yaml.org,2002:binary' - o.value.unpack('m').first - when '!str', 'tag:yaml.org,2002:str' - o.value - when "!ruby/object:DateTime" - require 'date' - @ss.parse_time(o.value).to_datetime - when "!ruby/object:Complex" - Complex(o.value) - when "!ruby/object:Rational" - Rational(o.value) - when "!ruby/class", "!ruby/module" - resolve_class o.value - when "tag:yaml.org,2002:float", "!float" - Float(@ss.tokenize(o.value)) - when "!ruby/regexp" - o.value =~ /^\/(.*)\/([mixn]*)$/ - source = $1 - options = 0 - lang = nil - ($2 || '').split('').each do |option| - case option - when 'x' then options |= Regexp::EXTENDED - when 'i' then options |= Regexp::IGNORECASE - when 'm' then options |= Regexp::MULTILINE - when 'n' then options |= Regexp::NOENCODING - else lang = option - end - end - Regexp.new(*[source, options, lang].compact) - when "!ruby/range" - args = o.value.split(/([.]{2,3})/, 2).map { |s| - accept Nodes::Scalar.new(s) - } - args.push(args.delete_at(1) == '...') - Range.new(*args) - when /^!ruby\/sym(bol)?:?(.*)?$/ - o.value.to_sym - else - @ss.tokenize o.value - end - end - - def visit_Psych_Nodes_Mapping_with_class(object) - return revive(Psych.load_tags[object.tag], object) if Psych.load_tags[object.tag] - - case object.tag - when /^!ruby\/ActiveRecord:(.+)$/ - klass = resolve_class($1) - payload = Hash[*object.children.map { |c| accept c }] - id = payload["attributes"][klass.primary_key] - begin - klass.unscoped.find(id) - rescue ActiveRecord::RecordNotFound - raise Delayed::DeserializationError - end - when /^!ruby\/Mongoid:(.+)$/ - klass = resolve_class($1) - payload = Hash[*object.children.map { |c| accept c }] - begin - klass.find(payload["attributes"]["_id"]) - rescue Mongoid::Errors::DocumentNotFound - raise Delayed::DeserializationError - end - when /^!ruby\/DataMapper:(.+)$/ - klass = resolve_class($1) - payload = Hash[*object.children.map { |c| accept c }] - begin - primary_keys = klass.properties.select { |p| p.key? } - key_names = primary_keys.map { |p| p.name.to_s } - klass.get!(*key_names.map { |k| payload["attributes"][k] }) - rescue DataMapper::ObjectNotFoundError - raise Delayed::DeserializationError - end - else - visit_Psych_Nodes_Mapping_without_class(object) - end - end - alias_method_chain :visit_Psych_Nodes_Mapping, :class - - def resolve_class_with_constantize(klass_name) - klass_name.constantize - rescue - resolve_class_without_constantize(klass_name) - end - alias_method_chain :resolve_class, :constantize - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/railtie.rb b/vendor/plugins/delayed_job/lib/delayed/railtie.rb deleted file mode 100644 index 19567c1..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/railtie.rb +++ /dev/null @@ -1,16 +0,0 @@ -require 'delayed_job' -require 'rails' - -module Delayed - class Railtie < Rails::Railtie - initializer :after_initialize do - ActiveSupport.on_load(:action_mailer) do - ActionMailer::Base.send(:extend, Delayed::DelayMail) - end - end - - rake_tasks do - load 'delayed/tasks.rb' - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/recipes.rb b/vendor/plugins/delayed_job/lib/delayed/recipes.rb deleted file mode 100644 index 18f8a16..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/recipes.rb +++ /dev/null @@ -1,54 +0,0 @@ -# Capistrano Recipes for managing delayed_job -# -# Add these callbacks to have the delayed_job process restart when the server -# is restarted: -# -# after "deploy:stop", "delayed_job:stop" -# after "deploy:start", "delayed_job:start" -# after "deploy:restart", "delayed_job:restart" -# -# If you want to use command line options, for example to start multiple workers, -# define a Capistrano variable delayed_job_args: -# -# set :delayed_job_args, "-n 2" -# -# If you've got delayed_job workers running on a servers, you can also specify -# which servers have delayed_job running and should be restarted after deploy. -# -# set :delayed_job_server_role, :worker -# - -Capistrano::Configuration.instance.load do - namespace :delayed_job do - def rails_env - fetch(:rails_env, false) ? "RAILS_ENV=#{fetch(:rails_env)}" : '' - end - - def args - fetch(:delayed_job_args, "") - end - - def roles - fetch(:delayed_job_server_role, :app) - end - - def delayed_job_command - fetch(:delayed_job_command, "script/delayed_job") - end - - desc "Stop the delayed_job process" - task :stop, :roles => lambda { roles } do - run "cd #{current_path};#{rails_env} #{delayed_job_command} stop" - end - - desc "Start the delayed_job process" - task :start, :roles => lambda { roles } do - run "cd #{current_path};#{rails_env} #{delayed_job_command} start #{args}" - end - - desc "Restart the delayed_job process" - task :restart, :roles => lambda { roles } do - run "cd #{current_path};#{rails_env} #{delayed_job_command} restart #{args}" - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/serialization/active_record.rb b/vendor/plugins/delayed_job/lib/delayed/serialization/active_record.rb deleted file mode 100644 index e9d0d6b..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/serialization/active_record.rb +++ /dev/null @@ -1,15 +0,0 @@ -if defined?(ActiveRecord) - class ActiveRecord::Base - yaml_as "tag:ruby.yaml.org,2002:ActiveRecord" - - def self.yaml_new(klass, tag, val) - klass.unscoped.find(val['attributes'][klass.primary_key]) - rescue ActiveRecord::RecordNotFound - raise Delayed::DeserializationError, "ActiveRecord::RecordNotFound, class: #{klass} , primary key: #{val['attributes'][klass.primary_key]} " - end - - def to_yaml_properties - ['@attributes'] - end - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/syck_ext.rb b/vendor/plugins/delayed_job/lib/delayed/syck_ext.rb deleted file mode 100644 index 54e529f..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/syck_ext.rb +++ /dev/null @@ -1,34 +0,0 @@ -class Module - yaml_as "tag:ruby.yaml.org,2002:module" - - def self.yaml_new(klass, tag, val) - val.constantize - end - - def to_yaml(options = {}) - YAML.quick_emit(nil, options) do |out| - out.scalar(taguri, name, :plain) - end - end - - def yaml_tag_read_class(name) - # Constantize the object so that ActiveSupport can attempt - # its auto loading magic. Will raise LoadError if not successful. - name.constantize - name - end -end - -class Class - yaml_as "tag:ruby.yaml.org,2002:class" - remove_method :to_yaml if respond_to?(:to_yaml) && method(:to_yaml).owner == Class # use Module's to_yaml -end - -class Struct - def self.yaml_tag_read_class(name) - # Constantize the object so that ActiveSupport can attempt - # its auto loading magic. Will raise LoadError if not successful. - name.constantize - "Struct::#{ name }" - end -end diff --git a/vendor/plugins/delayed_job/lib/delayed/tasks.rb b/vendor/plugins/delayed_job/lib/delayed/tasks.rb deleted file mode 100644 index ce2d075..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/tasks.rb +++ /dev/null @@ -1,38 +0,0 @@ -namespace :jobs do - desc "Clear the delayed_job queue." - task :clear => :environment do - Delayed::Job.delete_all - end - - desc "Start a delayed_job worker." - task :work => :environment_options do - Delayed::Worker.new(@worker_options).start - end - - desc "Start a delayed_job worker and exit when all available jobs are complete." - task :workoff => :environment_options do - Delayed::Worker.new(@worker_options.merge({:exit_on_complete => true})).start - end - - task :environment_options => :environment do - @worker_options = { - :min_priority => ENV['MIN_PRIORITY'], - :max_priority => ENV['MAX_PRIORITY'], - :queues => (ENV['QUEUES'] || ENV['QUEUE'] || '').split(','), - :quiet => false - } - end - - desc "Exit with error status if any jobs older than max_age seconds haven't been attempted yet." - task :check, [:max_age] => :environment do |_, args| - args.with_defaults(:max_age => 300) - - unprocessed_jobs = Delayed::Job.where('attempts = 0 AND created_at < ?', Time.now - args[:max_age].to_i).count - - if unprocessed_jobs > 0 - fail "#{unprocessed_jobs} jobs older than #{args[:max_age]} seconds have not been processed yet" - end - - end - -end diff --git a/vendor/plugins/delayed_job/lib/delayed/worker.rb b/vendor/plugins/delayed_job/lib/delayed/worker.rb deleted file mode 100644 index fbc365f..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/worker.rb +++ /dev/null @@ -1,283 +0,0 @@ -require 'timeout' -require 'active_support/core_ext/numeric/time' -require 'active_support/core_ext/class/attribute_accessors' -require 'active_support/core_ext/kernel' -require 'active_support/core_ext/enumerable' -require 'logger' -require 'benchmark' - -module Delayed - class Worker - DEFAULT_LOG_LEVEL = Logger::INFO - DEFAULT_SLEEP_DELAY = 5 - DEFAULT_MAX_ATTEMPTS = 25 - DEFAULT_MAX_RUN_TIME = 4.hours - DEFAULT_DEFAULT_PRIORITY = 0 - DEFAULT_DELAY_JOBS = true - DEFAULT_QUEUES = [] - DEFAULT_READ_AHEAD = 5 - - cattr_accessor :min_priority, :max_priority, :max_attempts, :max_run_time, - :default_priority, :sleep_delay, :logger, :delay_jobs, :queues, - :read_ahead, :plugins, :destroy_failed_jobs, :exit_on_complete - - # Named queue into which jobs are enqueued by default - cattr_accessor :default_queue_name - - cattr_reader :backend - - # name_prefix is ignored if name is set directly - attr_accessor :name_prefix - - def self.reset - self.sleep_delay = DEFAULT_SLEEP_DELAY - self.max_attempts = DEFAULT_MAX_ATTEMPTS - self.max_run_time = DEFAULT_MAX_RUN_TIME - self.default_priority = DEFAULT_DEFAULT_PRIORITY - self.delay_jobs = DEFAULT_DELAY_JOBS - self.queues = DEFAULT_QUEUES - self.read_ahead = DEFAULT_READ_AHEAD - end - - reset - - # Add or remove plugins in this list before the worker is instantiated - self.plugins = [Delayed::Plugins::ClearLocks] - - # By default failed jobs are destroyed after too many attempts. If you want to keep them around - # (perhaps to inspect the reason for the failure), set this to false. - self.destroy_failed_jobs = true - - # By default, Signals INT and TERM set @exit, and the worker exits upon completion of the current job. - # If you would prefer to raise a SignalException and exit immediately you can use this. - # Be aware daemons uses TERM to stop and restart - # false - No exceptions will be raised - # :term - Will only raise an exception on TERM signals but INT will wait for the current job to finish - # true - Will raise an exception on TERM and INT - cattr_accessor :raise_signal_exceptions - self.raise_signal_exceptions = false - - self.logger = if defined?(Rails) - Rails.logger - elsif defined?(RAILS_DEFAULT_LOGGER) - RAILS_DEFAULT_LOGGER - end - - def self.backend=(backend) - if backend.is_a? Symbol - require "delayed/serialization/#{backend}" - require "delayed/backend/#{backend}" - backend = "Delayed::Backend::#{backend.to_s.classify}::Job".constantize - end - @@backend = backend - silence_warnings { ::Delayed.const_set(:Job, backend) } - end - - def self.guess_backend - warn "[DEPRECATION] guess_backend is deprecated. Please remove it from your code." - end - - def self.before_fork - unless @files_to_reopen - @files_to_reopen = [] - ObjectSpace.each_object(File) do |file| - @files_to_reopen << file unless file.closed? - end - end - - backend.before_fork - end - - def self.after_fork - # Re-open file handles - @files_to_reopen.each do |file| - begin - file.reopen file.path, "a+" - file.sync = true - rescue ::Exception - end - end - - backend.after_fork - end - - def self.lifecycle - @lifecycle ||= Delayed::Lifecycle.new - end - - def initialize(options={}) - @quiet = options.has_key?(:quiet) ? options[:quiet] : true - @failed_reserve_count = 0 - - [:min_priority, :max_priority, :sleep_delay, :read_ahead, :queues, :exit_on_complete].each do |option| - self.class.send("#{option}=", options[option]) if options.has_key?(option) - end - - self.plugins.each { |klass| klass.new } - end - - # Every worker has a unique name which by default is the pid of the process. There are some - # advantages to overriding this with something which survives worker restarts: Workers can - # safely resume working on tasks which are locked by themselves. The worker will assume that - # it crashed before. - def name - return @name unless @name.nil? - "#{@name_prefix}host:#{Socket.gethostname} pid:#{Process.pid}" rescue "#{@name_prefix}pid:#{Process.pid}" - end - - # Sets the name of the worker. - # Setting the name to nil will reset the default worker name - def name=(val) - @name = val - end - - def start - trap('TERM') do - say 'Exiting...' - stop - raise SignalException.new('TERM') if self.class.raise_signal_exceptions - end - - trap('INT') do - say 'Exiting...' - stop - raise SignalException.new('INT') if self.class.raise_signal_exceptions && self.class.raise_signal_exceptions != :term - end - - say "Starting job worker" - - self.class.lifecycle.run_callbacks(:execute, self) do - loop do - self.class.lifecycle.run_callbacks(:loop, self) do - @realtime = Benchmark.realtime do - @result = work_off - end - end - - count = @result.sum - - if count.zero? - if self.class.exit_on_complete - say "No more jobs available. Exiting" - break - else - sleep(self.class.sleep_delay) unless stop? - end - else - say "#{count} jobs processed at %.4f j/s, %d failed" % [count / @realtime, @result.last] - end - - break if stop? - end - end - end - - def stop - @exit = true - end - - def stop? - !!@exit - end - - # Do num jobs and return stats on success/failure. - # Exit early if interrupted. - def work_off(num = 100) - success, failure = 0, 0 - - num.times do - case reserve_and_run_one_job - when true - success += 1 - when false - failure += 1 - else - break # leave if no work could be done - end - break if stop? # leave if we're exiting - end - - return [success, failure] - end - - def run(job) - job_say job, 'RUNNING' - runtime = Benchmark.realtime do - Timeout.timeout(self.class.max_run_time.to_i, WorkerTimeout) { job.invoke_job } - job.destroy - end - job_say job, 'COMPLETED after %.4f' % runtime - return true # did work - rescue DeserializationError => error - job.last_error = "#{error.message}\n#{error.backtrace.join("\n")}" - failed(job) - rescue Exception => error - self.class.lifecycle.run_callbacks(:error, self, job){ handle_failed_job(job, error) } - return false # work failed - end - - # Reschedule the job in the future (when a job fails). - # Uses an exponential scale depending on the number of failed attempts. - def reschedule(job, time = nil) - if (job.attempts += 1) < max_attempts(job) - time ||= job.reschedule_at - job.run_at = time - job.unlock - job.save! - else - job_say job, "REMOVED permanently because of #{job.attempts} consecutive failures", Logger::ERROR - failed(job) - end - end - - def failed(job) - self.class.lifecycle.run_callbacks(:failure, self, job) do - job.hook(:failure) - self.class.destroy_failed_jobs ? job.destroy : job.fail! - end - end - - def job_say(job, text, level = DEFAULT_LOG_LEVEL) - text = "Job #{job.name} (id=#{job.id}) #{text}" - say text, level - end - - def say(text, level = DEFAULT_LOG_LEVEL) - text = "[Worker(#{name})] #{text}" - puts text unless @quiet - logger.add level, "#{Time.now.strftime('%FT%T%z')}: #{text}" if logger - end - - def max_attempts(job) - job.max_attempts || self.class.max_attempts - end - - protected - - def handle_failed_job(job, error) - job.last_error = "#{error.message}\n#{error.backtrace.join("\n")}" - job_say job, "FAILED (#{job.attempts} prior attempts) with #{error.class.name}: #{error.message}", Logger::ERROR - reschedule(job) - end - - # Run the next job we can get an exclusive lock on. - # If no jobs are left we return nil - def reserve_and_run_one_job - job = reserve_job - self.class.lifecycle.run_callbacks(:perform, self, job){ run(job) } if job - end - - def reserve_job - job = Delayed::Job.reserve(self) - @failed_reserve_count = 0 - job - rescue Exception => error - say "Error while reserving job: #{error}" - Delayed::Job.recover_from(error) - @failed_reserve_count += 1 - raise FatalBackendError if @failed_reserve_count >= 10 - nil - end - end - -end diff --git a/vendor/plugins/delayed_job/lib/delayed/yaml_ext.rb b/vendor/plugins/delayed_job/lib/delayed/yaml_ext.rb deleted file mode 100644 index 4ef8272..0000000 --- a/vendor/plugins/delayed_job/lib/delayed/yaml_ext.rb +++ /dev/null @@ -1,10 +0,0 @@ -# These extensions allow properly serializing and autoloading of -# Classes, Modules and Structs - -require 'yaml' -if YAML.parser.class.name =~ /syck|yecht/i - require File.expand_path('../syck_ext', __FILE__) - require File.expand_path('../serialization/active_record', __FILE__) -else - require File.expand_path('../psych_ext', __FILE__) -end diff --git a/vendor/plugins/delayed_job/lib/delayed_job.rb b/vendor/plugins/delayed_job/lib/delayed_job.rb deleted file mode 100644 index cada396..0000000 --- a/vendor/plugins/delayed_job/lib/delayed_job.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'active_support' -require 'delayed/compatibility' -require 'delayed/exceptions' -require 'delayed/message_sending' -require 'delayed/performable_method' - -if defined?(ActionMailer) - require 'action_mailer/version' - require 'delayed/performable_mailer' -end - -require 'delayed/yaml_ext' -require 'delayed/lifecycle' -require 'delayed/plugin' -require 'delayed/plugins/clear_locks' -require 'delayed/backend/base' -require 'delayed/worker' -require 'delayed/deserialization_error' -require 'delayed/railtie' if defined?(Rails::Railtie) - -Object.send(:include, Delayed::MessageSending) -Module.send(:include, Delayed::MessageSending::ClassMethods) diff --git a/vendor/plugins/delayed_job/lib/generators/delayed_job/delayed_job_generator.rb b/vendor/plugins/delayed_job/lib/generators/delayed_job/delayed_job_generator.rb deleted file mode 100644 index 94157e3..0000000 --- a/vendor/plugins/delayed_job/lib/generators/delayed_job/delayed_job_generator.rb +++ /dev/null @@ -1,12 +0,0 @@ -require 'rails/generators' -require 'delayed/compatibility' - -class DelayedJobGenerator < Rails::Generators::Base - - self.source_paths << File.join(File.dirname(__FILE__), 'templates') - - def create_executable_file - template "script", "#{Delayed::Compatibility.executable_prefix}/delayed_job" - chmod "#{Delayed::Compatibility.executable_prefix}/delayed_job", 0755 - end -end diff --git a/vendor/plugins/delayed_job/lib/generators/delayed_job/templates/script b/vendor/plugins/delayed_job/lib/generators/delayed_job/templates/script deleted file mode 100644 index edf1959..0000000 --- a/vendor/plugins/delayed_job/lib/generators/delayed_job/templates/script +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env ruby - -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment')) -require 'delayed/command' -Delayed::Command.new(ARGV).daemonize diff --git a/vendor/plugins/delayed_job/recipes/delayed_job.rb b/vendor/plugins/delayed_job/recipes/delayed_job.rb deleted file mode 100644 index 05d4baa..0000000 --- a/vendor/plugins/delayed_job/recipes/delayed_job.rb +++ /dev/null @@ -1 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'delayed', 'recipes')) diff --git a/vendor/plugins/delayed_job/spec/autoloaded/clazz.rb b/vendor/plugins/delayed_job/spec/autoloaded/clazz.rb deleted file mode 100644 index 5c5756d..0000000 --- a/vendor/plugins/delayed_job/spec/autoloaded/clazz.rb +++ /dev/null @@ -1,7 +0,0 @@ -# Make sure this file does not get required manually -module Autoloaded - class Clazz - def perform - end - end -end diff --git a/vendor/plugins/delayed_job/spec/autoloaded/instance_clazz.rb b/vendor/plugins/delayed_job/spec/autoloaded/instance_clazz.rb deleted file mode 100644 index c6e4d4a..0000000 --- a/vendor/plugins/delayed_job/spec/autoloaded/instance_clazz.rb +++ /dev/null @@ -1,6 +0,0 @@ -module Autoloaded - class InstanceClazz - def perform - end - end -end diff --git a/vendor/plugins/delayed_job/spec/autoloaded/instance_struct.rb b/vendor/plugins/delayed_job/spec/autoloaded/instance_struct.rb deleted file mode 100644 index 3b8a8ff..0000000 --- a/vendor/plugins/delayed_job/spec/autoloaded/instance_struct.rb +++ /dev/null @@ -1,6 +0,0 @@ -module Autoloaded - class InstanceStruct < ::Struct.new(nil) - def perform - end - end -end diff --git a/vendor/plugins/delayed_job/spec/autoloaded/struct.rb b/vendor/plugins/delayed_job/spec/autoloaded/struct.rb deleted file mode 100644 index 3fbaeb4..0000000 --- a/vendor/plugins/delayed_job/spec/autoloaded/struct.rb +++ /dev/null @@ -1,7 +0,0 @@ -# Make sure this file does not get required manually -module Autoloaded - class Struct < ::Struct.new(nil) - def perform - end - end -end diff --git a/vendor/plugins/delayed_job/spec/delayed/backend/test.rb b/vendor/plugins/delayed_job/spec/delayed/backend/test.rb deleted file mode 100644 index fcf1d10..0000000 --- a/vendor/plugins/delayed_job/spec/delayed/backend/test.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'ostruct' - -# An in-memory backend suitable only for testing. Tries to behave as if it were an ORM. -module Delayed - module Backend - module Test - class Job - attr_accessor :id - attr_accessor :priority - attr_accessor :attempts - attr_accessor :handler - attr_accessor :last_error - attr_accessor :run_at - attr_accessor :locked_at - attr_accessor :locked_by - attr_accessor :failed_at - attr_accessor :queue - - include Delayed::Backend::Base - - cattr_accessor :id - self.id = 0 - - def initialize(hash = {}) - self.attempts = 0 - self.priority = 0 - self.id = (self.class.id += 1) - hash.each{|k,v| send(:"#{k}=", v)} - end - - @jobs = [] - def self.all - @jobs - end - - def self.count - all.size - end - - def self.delete_all - all.clear - end - - def self.create(attrs = {}) - new(attrs).tap do |o| - o.save - end - end - - def self.create!(*args); create(*args); end - - def self.clear_locks!(worker_name) - all.select{|j| j.locked_by == worker_name}.each {|j| j.locked_by = nil; j.locked_at = nil} - end - - # Find a few candidate jobs to run (in case some immediately get locked by others). - def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time) - jobs = all.select do |j| - j.run_at <= db_time_now && - (j.locked_at.nil? || j.locked_at < db_time_now - max_run_time || j.locked_by == worker_name) && - !j.failed? - end - - jobs = jobs.select{|j| Worker.queues.include?(j.queue)} if Worker.queues.any? - jobs = jobs.select{|j| j.priority >= Worker.min_priority} if Worker.min_priority - jobs = jobs.select{|j| j.priority <= Worker.max_priority} if Worker.max_priority - jobs.sort_by{|j| [j.priority, j.run_at]}[0..limit-1] - end - - # Lock this job for this worker. - # Returns true if we have the lock, false otherwise. - def lock_exclusively!(max_run_time, worker) - now = self.class.db_time_now - if locked_by != worker - # We don't own this job so we will update the locked_by name and the locked_at - self.locked_at = now - self.locked_by = worker - end - - return true - end - - def self.db_time_now - Time.current - end - - def update_attributes(attrs = {}) - attrs.each{|k,v| send(:"#{k}=", v)} - save - end - - def destroy - self.class.all.delete(self) - end - - def save - self.run_at ||= Time.current - - self.class.all << self unless self.class.all.include?(self) - true - end - - def save!; save; end - - def reload - reset - self - end - end - end - end -end diff --git a/vendor/plugins/delayed_job/spec/delayed/serialization/test.rb b/vendor/plugins/delayed_job/spec/delayed/serialization/test.rb deleted file mode 100644 index e69de29..0000000 --- a/vendor/plugins/delayed_job/spec/delayed/serialization/test.rb +++ /dev/null diff --git a/vendor/plugins/delayed_job/spec/helper.rb b/vendor/plugins/delayed_job/spec/helper.rb deleted file mode 100644 index 7cd1108..0000000 --- a/vendor/plugins/delayed_job/spec/helper.rb +++ /dev/null @@ -1,61 +0,0 @@ -require 'logger' -require 'rspec' - -require 'action_mailer' -require 'active_support/dependencies' -require 'active_record' - -require 'delayed_job' -require 'delayed/backend/shared_spec' - -require 'simplecov' -require 'coveralls' - -SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ - SimpleCov::Formatter::HTMLFormatter, - Coveralls::SimpleCov::Formatter -] -SimpleCov.start - -Delayed::Worker.logger = Logger.new('/tmp/dj.log') -ENV['RAILS_ENV'] = 'test' - -Delayed::Worker.backend = :test - -# Add this directory so the ActiveSupport autoloading works -ActiveSupport::Dependencies.autoload_paths << File.dirname(__FILE__) - -# Add this to simulate Railtie initializer being executed -ActionMailer::Base.send(:extend, Delayed::DelayMail) - - -# Used to test interactions between DJ and an ORM -ActiveRecord::Base.establish_connection :adapter => 'sqlite3', :database => ':memory:' -ActiveRecord::Base.logger = Delayed::Worker.logger -ActiveRecord::Migration.verbose = false - -ActiveRecord::Schema.define do - create_table :stories, :primary_key => :story_id, :force => true do |table| - table.string :text - table.boolean :scoped, :default => true - end -end - -class Story < ActiveRecord::Base - self.primary_key = 'story_id' - def tell; text; end - def whatever(n, _); tell*n; end - default_scope { where(:scoped => true) } - - handle_asynchronously :whatever -end - -RSpec.configure do |config| - config.after(:each) do - Delayed::Worker.reset - end - - config.expect_with :rspec do |c| - c.syntax = :expect - end -end diff --git a/vendor/plugins/delayed_job/spec/lifecycle_spec.rb b/vendor/plugins/delayed_job/spec/lifecycle_spec.rb deleted file mode 100644 index 0b31c90..0000000 --- a/vendor/plugins/delayed_job/spec/lifecycle_spec.rb +++ /dev/null @@ -1,67 +0,0 @@ -require 'helper' - -describe Delayed::Lifecycle do - let(:lifecycle) { Delayed::Lifecycle.new } - let(:callback) { lambda {|*args|} } - let(:arguments) { [1] } - let(:behavior) { double(Object, :before! => nil, :after! => nil, :inside! => nil) } - let(:wrapped_block) { Proc.new { behavior.inside! } } - - describe "before callbacks" do - before(:each) do - lifecycle.before(:execute, &callback) - end - - it "executes before wrapped block" do - callback.should_receive(:call).with(*arguments).ordered - behavior.should_receive(:inside!).ordered - lifecycle.run_callbacks :execute, *arguments, &wrapped_block - end - end - - describe "after callbacks" do - before(:each) do - lifecycle.after(:execute, &callback) - end - - it "executes after wrapped block" do - behavior.should_receive(:inside!).ordered - callback.should_receive(:call).with(*arguments).ordered - lifecycle.run_callbacks :execute, *arguments, &wrapped_block - end - end - - describe "around callbacks" do - before(:each) do - lifecycle.around(:execute) do |*args, &block| - behavior.before! - block.call(*args) - behavior.after! - end - end - - it "wraps a block" do - behavior.should_receive(:before!).ordered - behavior.should_receive(:inside!).ordered - behavior.should_receive(:after!).ordered - lifecycle.run_callbacks :execute, *arguments, &wrapped_block - end - - it "executes multiple callbacks in order" do - behavior.should_receive(:one).ordered - behavior.should_receive(:two).ordered - behavior.should_receive(:three).ordered - - lifecycle.around(:execute) { |*args, &block| behavior.one; block.call(*args) } - lifecycle.around(:execute) { |*args, &block| behavior.two; block.call(*args) } - lifecycle.around(:execute) { |*args, &block| behavior.three; block.call(*args) } - - lifecycle.run_callbacks(:execute, *arguments, &wrapped_block) - end - end - - it "raises if callback is executed with wrong number of parameters" do - lifecycle.before(:execute, &callback) - expect { lifecycle.run_callbacks(:execute, 1,2,3) {} }.to raise_error(ArgumentError, /1 parameter/) - end -end diff --git a/vendor/plugins/delayed_job/spec/message_sending_spec.rb b/vendor/plugins/delayed_job/spec/message_sending_spec.rb deleted file mode 100644 index a7abb3c..0000000 --- a/vendor/plugins/delayed_job/spec/message_sending_spec.rb +++ /dev/null @@ -1,122 +0,0 @@ -require 'helper' - -describe Delayed::MessageSending do - describe "handle_asynchronously" do - class Story - def tell!(arg);end - handle_asynchronously :tell! - end - - it "aliases original method" do - expect(Story.new).to respond_to(:tell_without_delay!) - expect(Story.new).to respond_to(:tell_with_delay!) - end - - it "creates a PerformableMethod" do - story = Story.create - expect { - job = story.tell!(1) - expect(job.payload_object.class).to eq(Delayed::PerformableMethod) - expect(job.payload_object.method_name).to eq(:tell_without_delay!) - expect(job.payload_object.args).to eq([1]) - }.to change { Delayed::Job.count } - end - - describe "with options" do - class Fable - cattr_accessor :importance - def tell;end - handle_asynchronously :tell, :priority => Proc.new { self.importance } - end - - it "sets the priority based on the Fable importance" do - Fable.importance = 10 - job = Fable.new.tell - expect(job.priority).to eq(10) - - Fable.importance = 20 - job = Fable.new.tell - expect(job.priority).to eq(20) - end - - describe "using a proc with parameters" do - class Yarn - attr_accessor :importance - def spin - end - handle_asynchronously :spin, :priority => Proc.new {|y| y.importance } - end - - it "sets the priority based on the Fable importance" do - job = Yarn.new.tap {|y| y.importance = 10 }.spin - expect(job.priority).to eq(10) - - job = Yarn.new.tap {|y| y.importance = 20 }.spin - expect(job.priority).to eq(20) - end - end - end - end - - context "delay" do - class FairyTail - attr_accessor :happy_ending - def self.princesses;end - def tell - @happy_ending = true - end - end - - after do - Delayed::Worker.default_queue_name = nil - end - - it "creates a new PerformableMethod job" do - expect { - job = "hello".delay.count('l') - expect(job.payload_object.class).to eq(Delayed::PerformableMethod) - expect(job.payload_object.method_name).to eq(:count) - expect(job.payload_object.args).to eq(['l']) - }.to change { Delayed::Job.count }.by(1) - end - - it "sets default priority" do - Delayed::Worker.default_priority = 99 - job = FairyTail.delay.to_s - expect(job.priority).to eq(99) - end - - it "sets default queue name" do - Delayed::Worker.default_queue_name = 'abbazabba' - job = FairyTail.delay.to_s - expect(job.queue).to eq('abbazabba') - end - - it "sets job options" do - run_at = Time.parse('2010-05-03 12:55 AM') - job = FairyTail.delay(:priority => 20, :run_at => run_at).to_s - expect(job.run_at).to eq(run_at) - expect(job.priority).to eq(20) - end - - it "does not delay the job when delay_jobs is false" do - Delayed::Worker.delay_jobs = false - fairy_tail = FairyTail.new - expect { - expect { - fairy_tail.delay.tell - }.to change(fairy_tail, :happy_ending).from(nil).to(true) - }.not_to change { Delayed::Job.count } - end - - it "does delay the job when delay_jobs is true" do - Delayed::Worker.delay_jobs = true - fairy_tail = FairyTail.new - expect { - expect { - fairy_tail.delay.tell - }.not_to change(fairy_tail, :happy_ending) - }.to change { Delayed::Job.count }.by(1) - end - end -end diff --git a/vendor/plugins/delayed_job/spec/performable_mailer_spec.rb b/vendor/plugins/delayed_job/spec/performable_mailer_spec.rb deleted file mode 100644 index 617ab84..0000000 --- a/vendor/plugins/delayed_job/spec/performable_mailer_spec.rb +++ /dev/null @@ -1,44 +0,0 @@ -require 'helper' - -require 'action_mailer' -class MyMailer < ActionMailer::Base - def signup(email) - mail :to => email, :subject => "Delaying Emails", :from => "delayedjob@example.com",:body => 'Delaying Emails Body' - end -end - -describe ActionMailer::Base do - describe "delay" do - it "enqueues a PerformableEmail job" do - expect { - job = MyMailer.delay.signup('john@example.com') - expect(job.payload_object.class).to eq(Delayed::PerformableMailer) - expect(job.payload_object.method_name).to eq(:signup) - expect(job.payload_object.args).to eq(['john@example.com']) - }.to change { Delayed::Job.count }.by(1) - end - end - - describe "delay on a mail object" do - it "raises an exception" do - expect { - MyMailer.signup('john@example.com').delay - }.to raise_error(RuntimeError) - end - end - - describe Delayed::PerformableMailer do - describe "perform" do - it "calls the method and #deliver on the mailer" do - email = double('email', :deliver => true) - mailer_class = double('MailerClass', :signup => email) - mailer = Delayed::PerformableMailer.new(mailer_class, :signup, ['john@example.com']) - - mailer_class.should_receive(:signup).with('john@example.com') - email.should_receive(:deliver) - mailer.perform - end - end - end - -end diff --git a/vendor/plugins/delayed_job/spec/performable_method_spec.rb b/vendor/plugins/delayed_job/spec/performable_method_spec.rb deleted file mode 100644 index a116860..0000000 --- a/vendor/plugins/delayed_job/spec/performable_method_spec.rb +++ /dev/null @@ -1,136 +0,0 @@ -require 'helper' - -describe Delayed::PerformableMethod do - describe "perform" do - before do - @method = Delayed::PerformableMethod.new("foo", :count, ['o']) - end - - context "with the persisted record cannot be found" do - before do - @method.object = nil - end - - it "does nothing if object is nil" do - expect{@method.perform}.not_to raise_error - end - end - - it "calls the method on the object" do - @method.object.should_receive(:count).with('o') - @method.perform - end - end - - it "raises a NoMethodError if target method doesn't exist" do - expect { - Delayed::PerformableMethod.new(Object, :method_that_does_not_exist, []) - }.to raise_error(NoMethodError) - end - - it "does not raise NoMethodError if target method is private" do - clazz = Class.new do - def private_method - end - private :private_method - end - expect { - Delayed::PerformableMethod.new(clazz.new, :private_method, []) - }.not_to raise_error - end - - describe "hooks" do - %w(before after success).each do |hook| - it "delegates #{hook} hook to object" do - story = Story.create - job = story.delay.tell - - story.should_receive(hook).with(job) - job.invoke_job - end - end - - %w(before after success).each do |hook| - it "delegates #{hook} hook to object" do - story = Story.create - job = story.delay.tell - - story.should_receive(hook).with(job) - job.invoke_job - end - end - - it "delegates enqueue hook to object" do - story = Story.create - story.should_receive(:enqueue).with(an_instance_of(Delayed::Job)) - story.delay.tell - end - - it "delegates error hook to object" do - story = Story.create - story.should_receive(:error).with(an_instance_of(Delayed::Job), an_instance_of(RuntimeError)) - story.should_receive(:tell).and_raise(RuntimeError) - expect { story.delay.tell.invoke_job }.to raise_error - end - - it "delegates error hook to object when delay_jobs = false" do - story = Story.create - story.should_receive(:error).with(an_instance_of(Delayed::Job), an_instance_of(RuntimeError)) - story.should_receive(:tell).and_raise(RuntimeError) - expect { story.delay.tell.invoke_job }.to raise_error - end - - it "delegates failure hook to object" do - method = Delayed::PerformableMethod.new("object", :size, []) - method.object.should_receive(:failure) - method.failure - end - - context 'with delay_job == false' do - before do - Delayed::Worker.delay_jobs = false - end - - after do - Delayed::Worker.delay_jobs = true - end - - %w(before after success).each do |hook| - it "delegates #{hook} hook to object" do - story = Story.create - story.should_receive(hook).with(an_instance_of(Delayed::Job)) - story.delay.tell - end - end - - %w(before after success).each do |hook| - it "delegates #{hook} hook to object" do - story = Story.create - story.should_receive(hook).with(an_instance_of(Delayed::Job)) - story.delay.tell - end - end - - it "delegates error hook to object" do - story = Story.create - story.should_receive(:error).with(an_instance_of(Delayed::Job), an_instance_of(RuntimeError)) - story.should_receive(:tell).and_raise(RuntimeError) - expect { story.delay.tell }.to raise_error - end - - it "delegates error hook to object when delay_jobs = false" do - story = Story.create - story.should_receive(:error).with(an_instance_of(Delayed::Job), an_instance_of(RuntimeError)) - story.should_receive(:tell).and_raise(RuntimeError) - expect { story.delay.tell }.to raise_error - end - - it "delegates failure hook to object when delay_jobs = false" do - Delayed::Worker.delay_jobs = false - method = Delayed::PerformableMethod.new("object", :size, []) - method.object.should_receive(:failure) - method.failure - end - end - end -end diff --git a/vendor/plugins/delayed_job/spec/sample_jobs.rb b/vendor/plugins/delayed_job/spec/sample_jobs.rb deleted file mode 100644 index 30a6183..0000000 --- a/vendor/plugins/delayed_job/spec/sample_jobs.rb +++ /dev/null @@ -1,75 +0,0 @@ -class NamedJob < Struct.new(:perform) - def display_name - 'named_job' - end -end - -class SimpleJob - cattr_accessor :runs; self.runs = 0 - def perform; @@runs += 1; end -end - -class ErrorJob - cattr_accessor :runs; self.runs = 0 - def perform; raise 'did not work'; end -end - -class CustomRescheduleJob < Struct.new(:offset) - cattr_accessor :runs; self.runs = 0 - def perform; raise 'did not work'; end - def reschedule_at(time, attempts); time + offset; end -end - -class LongRunningJob - def perform; sleep 250; end -end - -class OnPermanentFailureJob < SimpleJob - def failure; end - def max_attempts; 1; end -end - -module M - class ModuleJob - cattr_accessor :runs; self.runs = 0 - def perform; @@runs += 1; end - end -end - -class CallbackJob - cattr_accessor :messages - - def enqueue(job) - self.class.messages << 'enqueue' - end - - def before(job) - self.class.messages << 'before' - end - - def perform - self.class.messages << 'perform' - end - - def after(job) - self.class.messages << 'after' - end - - def success(job) - self.class.messages << 'success' - end - - def error(job, error) - self.class.messages << "error: #{error.class}" - end - - def failure(job) - self.class.messages << 'failure' - end -end - -class EnqueueJobMod < SimpleJob - def enqueue(job) - job.run_at = 20.minutes.from_now - end -end diff --git a/vendor/plugins/delayed_job/spec/test_backend_spec.rb b/vendor/plugins/delayed_job/spec/test_backend_spec.rb deleted file mode 100644 index 2840ef3..0000000 --- a/vendor/plugins/delayed_job/spec/test_backend_spec.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'helper' - -describe Delayed::Backend::Test::Job do - it_should_behave_like 'a delayed_job backend' - - describe "#reload" do - it "causes the payload object to be reloaded" do - job = "foo".delay.length - o = job.payload_object - expect(o.object_id).not_to eq(job.reload.payload_object.object_id) - end - end -end diff --git a/vendor/plugins/delayed_job/spec/worker_spec.rb b/vendor/plugins/delayed_job/spec/worker_spec.rb deleted file mode 100644 index d57ad7a..0000000 --- a/vendor/plugins/delayed_job/spec/worker_spec.rb +++ /dev/null @@ -1,102 +0,0 @@ -require 'helper' - -describe Delayed::Worker do - describe "backend=" do - before do - @clazz = Class.new - Delayed::Worker.backend = @clazz - end - - after do - Delayed::Worker.backend = :test - end - - it "sets the Delayed::Job constant to the backend" do - expect(Delayed::Job).to eq(@clazz) - end - - it "sets backend with a symbol" do - Delayed::Worker.backend = :test - expect(Delayed::Worker.backend).to eq(Delayed::Backend::Test::Job) - end - end - - describe "job_say" do - before do - @worker = Delayed::Worker.new - @job = double('job', :id => 123, :name => 'ExampleJob') - end - - it "logs with job name and id" do - @worker.should_receive(:say). - with('Job ExampleJob (id=123) message', Delayed::Worker::DEFAULT_LOG_LEVEL) - @worker.job_say(@job, 'message') - end - end - - context "worker read-ahead" do - before do - @read_ahead = Delayed::Worker.read_ahead - end - - after do - Delayed::Worker.read_ahead = @read_ahead - end - - it "reads five jobs" do - Delayed::Job.should_receive(:find_available).with(anything, 5, anything).and_return([]) - Delayed::Job.reserve(Delayed::Worker.new) - end - - it "reads a configurable number of jobs" do - Delayed::Worker.read_ahead = 15 - Delayed::Job.should_receive(:find_available).with(anything, Delayed::Worker.read_ahead, anything).and_return([]) - Delayed::Job.reserve(Delayed::Worker.new) - end - end - - context "worker exit on complete" do - before do - Delayed::Worker.exit_on_complete = true - end - - after do - Delayed::Worker.exit_on_complete = false - end - - it "exits the loop when no jobs are available" do - worker = Delayed::Worker.new - Timeout::timeout(2) do - worker.start - end - end - end - - context "worker job reservation" do - before do - Delayed::Worker.exit_on_complete = true - end - - after do - Delayed::Worker.exit_on_complete = false - end - - it "handles error during job reservation" do - Delayed::Job.should_receive(:reserve).and_raise(Exception) - Delayed::Worker.new.work_off - end - - it "gives up after 10 backend failures" do - Delayed::Job.stub(:reserve).and_raise(Exception) - worker = Delayed::Worker.new - 9.times { worker.work_off } - expect(lambda { worker.work_off }).to raise_exception - end - - it "allows the backend to attempt recovery from reservation errors" do - Delayed::Job.should_receive(:reserve).and_raise(Exception) - Delayed::Job.should_receive(:recover_from).with(instance_of(Exception)) - Delayed::Worker.new.work_off - end - end -end diff --git a/vendor/plugins/delayed_job/spec/yaml_ext_spec.rb b/vendor/plugins/delayed_job/spec/yaml_ext_spec.rb deleted file mode 100644 index d6edfa7..0000000 --- a/vendor/plugins/delayed_job/spec/yaml_ext_spec.rb +++ /dev/null @@ -1,35 +0,0 @@ -require 'helper' - -describe "YAML" do - it "autoloads classes" do - expect { - yaml = "--- !ruby/class Autoloaded::Clazz\n" - expect(YAML.load(yaml)).to eq(Autoloaded::Clazz) - }.not_to raise_error - end - - it "autoloads the class of a struct" do - expect { - yaml = "--- !ruby/class Autoloaded::Struct\n" - expect(YAML.load(yaml)).to eq(Autoloaded::Struct) - }.not_to raise_error - end - - it "autoloads the class for the instance of a struct" do - expect { - yaml = "--- !ruby/struct:Autoloaded::InstanceStruct {}" - expect(YAML.load(yaml).class).to eq(Autoloaded::InstanceStruct) - }.not_to raise_error - end - - it "autoloads the class for the instance" do - expect { - yaml = "--- !ruby/object:Autoloaded::InstanceClazz {}\n" - expect(YAML.load(yaml).class).to eq(Autoloaded::InstanceClazz) - }.not_to raise_error - end - - it "does not throw an uninitialized constant Syck::Syck when using YAML.load with poorly formed yaml" do - expect{ YAML.load(YAML.dump("foo: *bar"))}.not_to raise_error - end -end diff --git a/vendor/plugins/delayed_job_active_record/.rspec b/vendor/plugins/delayed_job_active_record/.rspec deleted file mode 100644 index ba44b74..0000000 --- a/vendor/plugins/delayed_job_active_record/.rspec +++ /dev/null @@ -1,2 +0,0 @@ ---color ---fail-fast diff --git a/vendor/plugins/delayed_job_active_record/.travis.yml b/vendor/plugins/delayed_job_active_record/.travis.yml deleted file mode 100644 index 2550250..0000000 --- a/vendor/plugins/delayed_job_active_record/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: ruby -before_script: - - mysql -e 'create database delayed_job_test;' - - psql -c 'create database delayed_job_test;' -U postgres -script: bundle exec rspec -gemfile: - - gemfiles/mysql/3-0.gemfile - - gemfiles/mysql/3-1.gemfile - - gemfiles/mysql/3-2.gemfile - - gemfiles/mysql/4-0.gemfile - - gemfiles/postgresql/3-0.gemfile - - gemfiles/postgresql/3-1.gemfile - - gemfiles/postgresql/3-2.gemfile - - gemfiles/postgresql/4-0.gemfile - - gemfiles/sqlite3/3-0.gemfile - - gemfiles/sqlite3/3-1.gemfile - - gemfiles/sqlite3/3-2.gemfile - - gemfiles/sqlite3/4-0.gemfile - - gemfiles/sqlite3/4-0-protected_attributes.gemfile -rvm: - - rbx-19mode - - jruby-19mode - - 1.9.3 - - 2.0.0 -matrix: - allow_failures: - - rvm: rbx-19mode - - rvm: jruby-19mode diff --git a/vendor/plugins/delayed_job_active_record/CONTRIBUTING.md b/vendor/plugins/delayed_job_active_record/CONTRIBUTING.md deleted file mode 100644 index c154663..0000000 --- a/vendor/plugins/delayed_job_active_record/CONTRIBUTING.md +++ /dev/null @@ -1,14 +0,0 @@ -## How to contribute - -If you find what looks like a bug: - -* Search the [mailing list](http://groups.google.com/group/delayed_job) to see if anyone else had the same issue. -* Check the [GitHub issue tracker](http://github.com/collectiveidea/delayed_job_active_record/issues/) to see if anyone else has reported issue. -* If you don't see anything, create an issue with information on how to reproduce it. - -If you want to contribute an enhancement or a fix: - -* Fork the project on github. -* Make your changes with tests. -* Commit the changes without making changes to the Rakefile or any other files that aren't related to your enhancement or fix -* Send a pull request. diff --git a/vendor/plugins/delayed_job_active_record/Gemfile b/vendor/plugins/delayed_job_active_record/Gemfile deleted file mode 100644 index 7b288e0..0000000 --- a/vendor/plugins/delayed_job_active_record/Gemfile +++ /dev/null @@ -1,28 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'activerecord-jdbcmysql-adapter' - gem 'jdbc-mysql' - - gem 'activerecord-jdbcpostgresql-adapter' - gem 'jdbc-postgres' - - gem 'activerecord-jdbcsqlite3-adapter' - gem 'jdbc-sqlite3' - end - - platforms :ruby, :mswin, :mingw do - gem 'mysql', '~> 2.8.1' - gem 'pg' - gem 'sqlite3' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false -end - -gemspec diff --git a/vendor/plugins/delayed_job_active_record/LICENSE.md b/vendor/plugins/delayed_job_active_record/LICENSE.md deleted file mode 100644 index 759ff02..0000000 --- a/vendor/plugins/delayed_job_active_record/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2005 Tobias Lütke - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOa AND -NONINFRINGEMENT. IN NO EVENT SaALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/plugins/delayed_job_active_record/README.md b/vendor/plugins/delayed_job_active_record/README.md deleted file mode 100644 index a546a38..0000000 --- a/vendor/plugins/delayed_job_active_record/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# DelayedJob ActiveRecord Backend - -[![Gem Version](https://badge.fury.io/rb/delayed_job_active_record.png)](https://rubygems.org/gems/delayed_job_active_record) -[![Build Status](https://travis-ci.org/collectiveidea/delayed_job_active_record.png)](https://travis-ci.org/collectiveidea/delayed_job_active_record) -[![Dependency Status](https://gemnasium.com/collectiveidea/delayed_job_active_record.png)](https://gemnasium.com/collectiveidea/delayed_job_active_record) -[![Code Climate](https://codeclimate.com/github/collectiveidea/delayed_job_active_record.png)](https://codeclimate.com/github/collectiveidea/delayed_job_active_record) -[![Coverage Status](https://coveralls.io/repos/collectiveidea/delayed_job_active_record/badge.png?branch=master)](https://coveralls.io/r/collectiveidea/delayed_job_active_record) - -## Installation - -Add the gem to your Gemfile: - - gem 'delayed_job_active_record' - -Run `bundle install`. - -If you're using Rails, run the generator to create the migration for the -delayed_job table. - - rails g delayed_job:active_record - rake db:migrate - -## Upgrading from 2.x to 3.0.0 - -If you're upgrading from Delayed Job 2.x, run the upgrade generator to create a -migration to add a column to your delayed_jobs table. - - rails g delayed_job:upgrade - rake db:migrate - -That's it. Use [delayed_job as normal](http://github.com/collectiveidea/delayed_job). diff --git a/vendor/plugins/delayed_job_active_record/Rakefile b/vendor/plugins/delayed_job_active_record/Rakefile deleted file mode 100644 index 0932015..0000000 --- a/vendor/plugins/delayed_job_active_record/Rakefile +++ /dev/null @@ -1,35 +0,0 @@ -# -*- encoding: utf-8 -*- -require "bundler/gem_helper" -Bundler::GemHelper.install_tasks - -require "rspec/core/rake_task" - -ADAPTERS = %w(mysql postgresql sqlite3) - -ADAPTERS.each do |adapter| - desc "Run RSpec code examples for #{adapter} adapter" - RSpec::Core::RakeTask.new(adapter => "#{adapter}:adapter") - - namespace adapter do - task :adapter do - ENV["ADAPTER"] = adapter - end - end -end - -task :coverage do - ENV["COVERAGE"] = "true" -end - -task :adapter do - ENV["ADAPTER"] = nil -end - -Rake::Task[:spec].enhance do - require "simplecov" - require "coveralls" - - Coveralls::SimpleCov::Formatter.new.format(SimpleCov.result) -end - -task default: ([:coverage] + ADAPTERS + [:adapter]) diff --git a/vendor/plugins/delayed_job_active_record/delayed_job_active_record.gemspec b/vendor/plugins/delayed_job_active_record/delayed_job_active_record.gemspec deleted file mode 100644 index a480c5e..0000000 --- a/vendor/plugins/delayed_job_active_record/delayed_job_active_record.gemspec +++ /dev/null @@ -1,19 +0,0 @@ -# coding: utf-8 - -Gem::Specification.new do |spec| - spec.add_dependency 'activerecord', ['>= 3.0', '< 4.1'] - spec.add_dependency 'delayed_job', ['>= 3.0', '< 4.1'] - spec.authors = ["Brian Ryckbost", "Matt Griffin", "Erik Michaels-Ober"] - spec.description = 'ActiveRecord backend for Delayed::Job, originally authored by Tobias Lütke' - spec.email = ['bryckbost@gmail.com', 'matt@griffinonline.org', 'sferik@gmail.com'] - spec.files = %w(CONTRIBUTING.md LICENSE.md README.md Rakefile delayed_job_active_record.gemspec) - spec.files += Dir.glob("lib/**/*.rb") - spec.files += Dir.glob("spec/**/*") - spec.homepage = 'http://github.com/collectiveidea/delayed_job_active_record' - spec.licenses = ['MIT'] - spec.name = 'delayed_job_active_record' - spec.require_paths = ['lib'] - spec.summary = 'ActiveRecord backend for DelayedJob' - spec.test_files = Dir.glob("spec/**/*") - spec.version = '4.0.0' -end diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/mysql/3-0.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/mysql/3-0.gemfile deleted file mode 100644 index 74e564a..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/mysql/3-0.gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcmysql-adapter' - gem 'jdbc-mysql' - end - - platforms :ruby, :mswin, :mingw do - gem 'mysql', '~> 2.8.1' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 3.0.0" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/mysql/3-1.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/mysql/3-1.gemfile deleted file mode 100644 index fc883ed..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/mysql/3-1.gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcmysql-adapter' - gem 'jdbc-mysql' - end - - platforms :ruby, :mswin, :mingw do - gem 'mysql', '~> 2.8.1' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 3.1.0" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/mysql/3-2.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/mysql/3-2.gemfile deleted file mode 100644 index f77341c..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/mysql/3-2.gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcmysql-adapter' - gem 'jdbc-mysql' - end - - platforms :ruby, :mswin, :mingw do - gem 'mysql', '~> 2.8.1' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 3.2.0" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/mysql/4-0.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/mysql/4-0.gemfile deleted file mode 100644 index 9328916..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/mysql/4-0.gemfile +++ /dev/null @@ -1,25 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcmysql-adapter' - gem 'jdbc-mysql' - end - - platforms :ruby, :mswin, :mingw do - gem 'mysql', '~> 2.9' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 4.0.0.beta" - - gem 'delayed_job', "~> 4.0.0.beta" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/3-0.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/3-0.gemfile deleted file mode 100644 index 3f39d4a..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/3-0.gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcpostgresql-adapter' - gem 'jdbc-postgres' - end - - platforms :ruby, :mswin, :mingw do - gem 'pg' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 3.0.0" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/3-1.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/3-1.gemfile deleted file mode 100644 index cf2b1fc..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/3-1.gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcpostgresql-adapter' - gem 'jdbc-postgres' - end - - platforms :ruby, :mswin, :mingw do - gem 'pg' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 3.1.0" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/3-2.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/3-2.gemfile deleted file mode 100644 index b5c9026..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/3-2.gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcpostgresql-adapter' - gem 'jdbc-postgres' - end - - platforms :ruby, :mswin, :mingw do - gem 'pg' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 3.2.0" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/4-0.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/4-0.gemfile deleted file mode 100644 index fd576bc..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/postgresql/4-0.gemfile +++ /dev/null @@ -1,25 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcpostgresql-adapter' - gem 'jdbc-postgres' - end - - platforms :ruby, :mswin, :mingw do - gem 'pg' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 4.0.0.beta" - - gem 'delayed_job', "~> 4.0.0.beta" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/3-0.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/3-0.gemfile deleted file mode 100644 index 0688e17..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/3-0.gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'jruby-openssl' - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcsqlite3-adapter' - end - - platforms :ruby, :mswin, :mingw do - gem 'sqlite3' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 3.0.0" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/3-1.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/3-1.gemfile deleted file mode 100644 index b693196..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/3-1.gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'jruby-openssl' - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcsqlite3-adapter' - end - - platforms :ruby, :mswin, :mingw do - gem 'sqlite3' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 3.1.0" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/3-2.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/3-2.gemfile deleted file mode 100644 index 2e2ca7a..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/3-2.gemfile +++ /dev/null @@ -1,23 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'jruby-openssl' - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcsqlite3-adapter' - end - - platforms :ruby, :mswin, :mingw do - gem 'sqlite3' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 3.2.0" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/4-0-protected_attributes.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/4-0-protected_attributes.gemfile deleted file mode 100644 index f25516e..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/4-0-protected_attributes.gemfile +++ /dev/null @@ -1,26 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'jruby-openssl' - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcsqlite3-adapter' - end - - platforms :ruby, :mswin, :mingw do - gem 'sqlite3' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11', :require => false - gem 'simplecov', :require => false - - gem 'activerecord', "~> 4.0.0.beta" - gem 'protected_attributes' - - gem 'delayed_job', "~> 4.0.0.beta", :require => false -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/4-0.gemfile b/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/4-0.gemfile deleted file mode 100644 index 3b70d1b..0000000 --- a/vendor/plugins/delayed_job_active_record/gemfiles/sqlite3/4-0.gemfile +++ /dev/null @@ -1,25 +0,0 @@ -source 'https://rubygems.org' - -gem 'rake' - -group :test do - platforms :jruby do - gem 'jruby-openssl' - gem 'activerecord-jdbc-adapter' - gem 'activerecord-jdbcsqlite3-adapter' - end - - platforms :ruby, :mswin, :mingw do - gem 'sqlite3' - end - - gem 'coveralls', :require => false - gem 'rspec', '>= 2.11' - gem 'simplecov', :require => false - - gem 'activerecord', "~> 4.0.0.beta" - - gem 'delayed_job', "~> 4.0.0.beta" -end - -gemspec :path => "../../" diff --git a/vendor/plugins/delayed_job_active_record/lib/delayed/backend/active_record.rb b/vendor/plugins/delayed_job_active_record/lib/delayed/backend/active_record.rb deleted file mode 100644 index 747c2f1..0000000 --- a/vendor/plugins/delayed_job_active_record/lib/delayed/backend/active_record.rb +++ /dev/null @@ -1,111 +0,0 @@ -require 'active_record/version' -module Delayed - module Backend - module ActiveRecord - # A job object that is persisted to the database. - # Contains the work object as a YAML field. - class Job < ::ActiveRecord::Base - include Delayed::Backend::Base - - if ::ActiveRecord::VERSION::MAJOR < 4 || defined?(::ActiveRecord::MassAssignmentSecurity) - attr_accessible :priority, :run_at, :queue, :payload_object, - :failed_at, :locked_at, :locked_by, :handler - end - - scope :by_priority, lambda { order('priority ASC, run_at ASC') } - - before_save :set_default_run_at - - def self.set_delayed_job_table_name - delayed_job_table_name = "#{::ActiveRecord::Base.table_name_prefix}delayed_jobs" - self.table_name = delayed_job_table_name - end - - self.set_delayed_job_table_name - - def self.ready_to_run(worker_name, max_run_time) - where('(run_at <= ? AND (locked_at IS NULL OR locked_at < ?) OR locked_by = ?) AND failed_at IS NULL', db_time_now, db_time_now - max_run_time, worker_name) - end - - def self.before_fork - ::ActiveRecord::Base.clear_all_connections! - end - - def self.after_fork - ::ActiveRecord::Base.establish_connection - end - - # When a worker is exiting, make sure we don't have any locked jobs. - def self.clear_locks!(worker_name) - where(:locked_by => worker_name).update_all(:locked_by => nil, :locked_at => nil) - end - - def self.reserve(worker, max_run_time = Worker.max_run_time) - # scope to filter to records that are "ready to run" - ready_scope = self.ready_to_run(worker.name, max_run_time) - - # scope to filter to the single next eligible job - ready_scope = ready_scope.where('priority >= ?', Worker.min_priority) if Worker.min_priority - ready_scope = ready_scope.where('priority <= ?', Worker.max_priority) if Worker.max_priority - ready_scope = ready_scope.where(:queue => Worker.queues) if Worker.queues.any? - ready_scope = ready_scope.by_priority - - now = self.db_time_now - - # Optimizations for faster lookups on some common databases - case self.connection.adapter_name - when "PostgreSQL" - # Custom SQL required for PostgreSQL because postgres does not support UPDATE...LIMIT - # This locks the single record 'FOR UPDATE' in the subquery (http://www.postgresql.org/docs/9.0/static/sql-select.html#SQL-FOR-UPDATE-SHARE) - # Note: active_record would attempt to generate UPDATE...LIMIT like sql for postgres if we use a .limit() filter, but it would not use - # 'FOR UPDATE' and we would have many locking conflicts - quoted_table_name = self.connection.quote_table_name(self.table_name) - subquery_sql = ready_scope.limit(1).lock(true).select('id').to_sql - reserved = self.find_by_sql(["UPDATE #{quoted_table_name} SET locked_at = ?, locked_by = ? WHERE id IN (#{subquery_sql}) RETURNING *", now, worker.name]) - reserved[0] - when "MySQL", "Mysql2" - # This works on MySQL and possibly some other DBs that support UPDATE...LIMIT. It uses separate queries to lock and return the job - count = ready_scope.limit(1).update_all(:locked_at => now, :locked_by => worker.name) - return nil if count == 0 - self.where(:locked_at => now, :locked_by => worker.name, :failed_at => nil).first - when "MSSQL", "Teradata" - # The MSSQL driver doesn't generate a limit clause when update_all is called directly - subsubquery_sql = ready_scope.limit(1).to_sql - # select("id") doesn't generate a subquery, so force a subquery - subquery_sql = "SELECT id FROM (#{subsubquery_sql}) AS x" - quoted_table_name = self.connection.quote_table_name(self.table_name) - sql = ["UPDATE #{quoted_table_name} SET locked_at = ?, locked_by = ? WHERE id IN (#{subquery_sql})", now, worker.name] - count = self.connection.execute(sanitize_sql(sql)) - return nil if count == 0 - # MSSQL JDBC doesn't support OUTPUT INSERTED.* for returning a result set, so query locked row - self.where(:locked_at => now, :locked_by => worker.name, :failed_at => nil).first - else - # This is our old fashion, tried and true, but slower lookup - ready_scope.limit(worker.read_ahead).detect do |job| - count = ready_scope.where(:id => job.id).update_all(:locked_at => now, :locked_by => worker.name) - count == 1 && job.reload - end - end - end - - # Get the current time (GMT or local depending on DB) - # Note: This does not ping the DB to get the time, so all your clients - # must have syncronized clocks. - def self.db_time_now - if Time.zone - Time.zone.now - elsif ::ActiveRecord::Base.default_timezone == :utc - Time.now.utc - else - Time.now - end - end - - def reload(*args) - reset - super - end - end - end - end -end diff --git a/vendor/plugins/delayed_job_active_record/lib/delayed_job_active_record.rb b/vendor/plugins/delayed_job_active_record/lib/delayed_job_active_record.rb deleted file mode 100644 index 08b8723..0000000 --- a/vendor/plugins/delayed_job_active_record/lib/delayed_job_active_record.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'active_record' -require 'delayed_job' -require 'delayed/backend/active_record' - -Delayed::Worker.backend = :active_record diff --git a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/active_record_generator.rb b/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/active_record_generator.rb deleted file mode 100644 index 762ac26..0000000 --- a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/active_record_generator.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'generators/delayed_job/delayed_job_generator' -require 'generators/delayed_job/next_migration_version' -require 'rails/generators/migration' -require 'rails/generators/active_record' - -# Extend the DelayedJobGenerator so that it creates an AR migration -module DelayedJob - class ActiveRecordGenerator < ::DelayedJobGenerator - include Rails::Generators::Migration - extend NextMigrationVersion - - self.source_paths << File.join(File.dirname(__FILE__), 'templates') - - def create_migration_file - migration_template 'migration.rb', 'db/migrate/create_delayed_jobs.rb' - end - - def self.next_migration_number dirname - ActiveRecord::Generators::Base.next_migration_number dirname - end - end -end diff --git a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/next_migration_version.rb b/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/next_migration_version.rb deleted file mode 100644 index e48ed62..0000000 --- a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/next_migration_version.rb +++ /dev/null @@ -1,14 +0,0 @@ -module DelayedJob - module NextMigrationVersion - # while methods have moved around this has been the implementation - # since ActiveRecord 3.0 - def next_migration_number(dirname) - next_migration_number = current_migration_number(dirname) + 1 - if ActiveRecord::Base.timestamped_migrations - [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % next_migration_number].max - else - "%.3d" % next_migration_number - end - end - end -end diff --git a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/templates/migration.rb b/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/templates/migration.rb deleted file mode 100644 index ec0dd93..0000000 --- a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/templates/migration.rb +++ /dev/null @@ -1,22 +0,0 @@ -class CreateDelayedJobs < ActiveRecord::Migration - def self.up - create_table :delayed_jobs, :force => true do |table| - table.integer :priority, :default => 0, :null => false # Allows some jobs to jump to the front of the queue - table.integer :attempts, :default => 0, :null => false # Provides for retries, but still fail eventually. - table.text :handler, :null => false # YAML-encoded string of the object that will do work - table.text :last_error # reason for last failure (See Note below) - table.datetime :run_at # When to run. Could be Time.zone.now for immediately, or sometime in the future. - table.datetime :locked_at # Set when a client is working on this object - table.datetime :failed_at # Set when all retries have failed (actually, by default, the record is deleted instead) - table.string :locked_by # Who is working on this object (if locked) - table.string :queue # The name of the queue this job is in - table.timestamps - end - - add_index :delayed_jobs, [:priority, :run_at], :name => 'delayed_jobs_priority' - end - - def self.down - drop_table :delayed_jobs - end -end diff --git a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/templates/upgrade_migration.rb b/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/templates/upgrade_migration.rb deleted file mode 100644 index 072c8d4..0000000 --- a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/templates/upgrade_migration.rb +++ /dev/null @@ -1,9 +0,0 @@ -class AddQueueToDelayedJobs < ActiveRecord::Migration - def self.up - add_column :delayed_jobs, :queue, :string - end - - def self.down - remove_column :delayed_jobs, :queue - end -end diff --git a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/upgrade_generator.rb b/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/upgrade_generator.rb deleted file mode 100644 index c62d4b8..0000000 --- a/vendor/plugins/delayed_job_active_record/lib/generators/delayed_job/upgrade_generator.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'generators/delayed_job/delayed_job_generator' -require 'generators/delayed_job/next_migration_version' -require 'rails/generators/migration' -require 'rails/generators/active_record' - -# Extend the DelayedJobGenerator so that it creates an AR migration -module DelayedJob - class UpgradeGenerator < ::DelayedJobGenerator - include Rails::Generators::Migration - extend NextMigrationVersion - - self.source_paths << File.join(File.dirname(__FILE__), 'templates') - - def create_migration_file - migration_template 'upgrade_migration.rb', 'db/migrate/add_queue_to_delayed_jobs.rb' - end - - def self.next_migration_number dirname - ActiveRecord::Generators::Base.next_migration_number dirname - end - end -end diff --git a/vendor/plugins/delayed_job_active_record/spec/database.yml b/vendor/plugins/delayed_job_active_record/spec/database.yml deleted file mode 100644 index 6f56eb4..0000000 --- a/vendor/plugins/delayed_job_active_record/spec/database.yml +++ /dev/null @@ -1,14 +0,0 @@ -mysql: - adapter: mysql - database: delayed_job_test - username: root - encoding: utf8 - -postgresql: - adapter: postgresql - database: delayed_job_test - username: postgres - -sqlite3: - adapter: sqlite3 - database: ":memory:" diff --git a/vendor/plugins/delayed_job_active_record/spec/delayed/backend/active_record_spec.rb b/vendor/plugins/delayed_job_active_record/spec/delayed/backend/active_record_spec.rb deleted file mode 100644 index 293fdc9..0000000 --- a/vendor/plugins/delayed_job_active_record/spec/delayed/backend/active_record_spec.rb +++ /dev/null @@ -1,81 +0,0 @@ -require 'helper' -require 'delayed/backend/active_record' - -describe Delayed::Backend::ActiveRecord::Job do - it_behaves_like 'a delayed_job backend' - - context "db_time_now" do - after do - Time.zone = nil - ActiveRecord::Base.default_timezone = :local - end - - it "returns time in current time zone if set" do - Time.zone = 'Eastern Time (US & Canada)' - expect(%(EST EDT)).to include(Delayed::Job.db_time_now.zone) - end - - it "returns UTC time if that is the AR default" do - Time.zone = nil - ActiveRecord::Base.default_timezone = :utc - expect(Delayed::Backend::ActiveRecord::Job.db_time_now.zone).to eq 'UTC' - end - - it "returns local time if that is the AR default" do - Time.zone = 'Central Time (US & Canada)' - ActiveRecord::Base.default_timezone = :local - expect(%w(CST CDT)).to include(Delayed::Backend::ActiveRecord::Job.db_time_now.zone) - end - end - - describe "after_fork" do - it "calls reconnect on the connection" do - ActiveRecord::Base.should_receive(:establish_connection) - Delayed::Backend::ActiveRecord::Job.after_fork - end - end - - describe "enqueue" do - it "allows enqueue hook to modify job at DB level" do - later = described_class.db_time_now + 20.minutes - job = Delayed::Backend::ActiveRecord::Job.enqueue :payload_object => EnqueueJobMod.new - expect(Delayed::Backend::ActiveRecord::Job.find(job.id).run_at).to be_within(1).of(later) - end - end - - if ::ActiveRecord::VERSION::MAJOR < 4 || defined?(::ActiveRecord::MassAssignmentSecurity) - context "ActiveRecord::Base.send(:attr_accessible, nil)" do - before do - Delayed::Backend::ActiveRecord::Job.send(:attr_accessible, nil) - end - - after do - Delayed::Backend::ActiveRecord::Job.send(:attr_accessible, *Delayed::Backend::ActiveRecord::Job.new.attributes.keys) - end - - it "is still accessible" do - job = Delayed::Backend::ActiveRecord::Job.enqueue :payload_object => EnqueueJobMod.new - expect(Delayed::Backend::ActiveRecord::Job.find(job.id).handler).to_not be_blank - end - end - end - - context "ActiveRecord::Base.table_name_prefix" do - it "when prefix is not set, use 'delayed_jobs' as table name" do - ::ActiveRecord::Base.table_name_prefix = nil - Delayed::Backend::ActiveRecord::Job.set_delayed_job_table_name - - expect(Delayed::Backend::ActiveRecord::Job.table_name).to eq 'delayed_jobs' - end - - it "when prefix is set, prepend it before default table name" do - ::ActiveRecord::Base.table_name_prefix = 'custom_' - Delayed::Backend::ActiveRecord::Job.set_delayed_job_table_name - - expect(Delayed::Backend::ActiveRecord::Job.table_name).to eq 'custom_delayed_jobs' - - ::ActiveRecord::Base.table_name_prefix = nil - Delayed::Backend::ActiveRecord::Job.set_delayed_job_table_name - end - end -end diff --git a/vendor/plugins/delayed_job_active_record/spec/delayed/serialization/active_record_spec.rb b/vendor/plugins/delayed_job_active_record/spec/delayed/serialization/active_record_spec.rb deleted file mode 100644 index 81e0ab8..0000000 --- a/vendor/plugins/delayed_job_active_record/spec/delayed/serialization/active_record_spec.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'helper' - -describe ActiveRecord do - it "loads classes with non-default primary key" do - expect { - YAML.load(Story.create.to_yaml) - }.not_to raise_error - end - - it "loads classes even if not in default scope" do - expect { - YAML.load(Story.create(:scoped => false).to_yaml) - }.not_to raise_error - end -end diff --git a/vendor/plugins/delayed_job_active_record/spec/helper.rb b/vendor/plugins/delayed_job_active_record/spec/helper.rb deleted file mode 100644 index 95894e9..0000000 --- a/vendor/plugins/delayed_job_active_record/spec/helper.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'simplecov' -require 'coveralls' - -SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ - SimpleCov::Formatter::HTMLFormatter, - Coveralls::SimpleCov::Formatter -] -SimpleCov.start - -require 'logger' -require 'rspec' - -begin - require 'protected_attributes' -rescue LoadError -end -require 'delayed_job_active_record' -require 'delayed/backend/shared_spec' - -Delayed::Worker.logger = Logger.new('/tmp/dj.log') -ENV['RAILS_ENV'] = 'test' - -db_adapter, gemfile = ENV["ADAPTER"], ENV["BUNDLE_GEMFILE"] -db_adapter ||= gemfile && gemfile[%r(gemfiles/(.*?)/)] && $1 -db_adapter ||= 'sqlite3' - -config = YAML.load(File.read('spec/database.yml')) -ActiveRecord::Base.establish_connection config[db_adapter] -ActiveRecord::Base.logger = Delayed::Worker.logger -ActiveRecord::Migration.verbose = false - -ActiveRecord::Schema.define do - create_table :delayed_jobs, :force => true do |table| - table.integer :priority, :default => 0 - table.integer :attempts, :default => 0 - table.text :handler - table.text :last_error - table.datetime :run_at - table.datetime :locked_at - table.datetime :failed_at - table.string :locked_by - table.string :queue - table.timestamps - end - - add_index :delayed_jobs, [:priority, :run_at], :name => 'delayed_jobs_priority' - - create_table :stories, :primary_key => :story_id, :force => true do |table| - table.string :text - table.boolean :scoped, :default => true - end -end - -# Purely useful for test cases... -class Story < ActiveRecord::Base - if ::ActiveRecord::VERSION::MAJOR < 4 && ActiveRecord::VERSION::MINOR < 2 - set_primary_key :story_id - else - self.primary_key = :story_id - end - def tell; text; end - def whatever(n, _); tell*n; end - default_scope { where(:scoped => true) } - - handle_asynchronously :whatever -end - -# Add this directory so the ActiveSupport autoloading works -ActiveSupport::Dependencies.autoload_paths << File.dirname(__FILE__) diff --git a/vendor/plugins/monkey_patches/will_paginate_check_finder_sql/init.rb b/vendor/plugins/monkey_patches/will_paginate_check_finder_sql/init.rb deleted file mode 100644 index 73a5496..0000000 --- a/vendor/plugins/monkey_patches/will_paginate_check_finder_sql/init.rb +++ /dev/null @@ -1,18 +0,0 @@ -# monkey patch to fix WillPaginate bug -# this was solved in will_paginate 3.x.pre, then remove this patch when upgrade to it -# -# http://sod.lighthouseapp.com/projects/17958/tickets/120-paginate-association-with-finder_sql-raises-typeerror -require 'will_paginate' - -WillPaginate::Finder::ClassMethods.module_eval do - def paginate_with_finder_sql(*args) - if respond_to?(:proxy_reflection) && !proxy_reflection.options[:finder_sql].nil? - # note: paginate_by_sql ignores the blocks. So don't pass the block - paginate_by_sql(@finder_sql, args.extract_options!) - else - paginate_without_finder_sql(*args) - end - end - # patch to deal with the custom_sql scenario - alias_method_chain :paginate, :finder_sql -end diff --git a/vendor/plugins/pothoven-attachment_fu/CHANGELOG b/vendor/plugins/pothoven-attachment_fu/CHANGELOG deleted file mode 100644 index 83a0f3a..0000000 --- a/vendor/plugins/pothoven-attachment_fu/CHANGELOG +++ /dev/null @@ -1,84 +0,0 @@ -* Aug 22, 2013 * -* Added cache-control header option and Ruby 1.9 fix for S3 from tricycle - -* Aug 21, 2013 * -* Added S3 :encrypted_storage option support from cschulte22 - -* Jul 5, 2013 -* Pull in changes from lchimonji10 to reformat README to RDoc format - -* Apr 10, 2013 * -* Ruby 2 compatibility fix -* Removed some lingering occurrences of RAILS_ROOT and RAILS_ENV -* clean up of gemspec file -* no longer package unnecessary files like the test files - -* Mar 12, 2013 * -* Pull in changes from https://github.com/aalong/attachment_fu to use Ruby 1.9.2 Tempfile naming strategy to fix conflicts with Sprockets (see https://github.com/aalong/attachment_fu/commit/938ec3b8597fbf82b1de8c98de12c4688463450a) - -* Feb 19, 2013 * -* Pull in changes from https://github.com/itkin/attachment_fu fork to fix mini magick - -* Nov 15, 2012 * -* Removed 'crop:' option as already included when prefixing geometry with a 'c'. Add note to docs. -* Added option to sharpen resized images ':sharpen_on_resize' - -* Oct 26, 2012 * -* Merged with https://github.com/tdd/attachment_fu fork to include GEM support for use in Rails 3.2, and bumped version to 3.2.x to indicate Rails 3.2 support. - -* Oct 25, 2012 * -* Fix to support Ruby 1.9.3 -* Image cropping support (append 'crop:' to desired file size when resizing) - -* Mar 15, 2010 * -* Added a symbol syntax for parent-type-based size spec: calls the corresponding method on the current asset instance to - get a Hash of required thumbnails. Lets us dynamically specify what would otherwise be hard-coded, which is useful - when the set of thumbnails for a given parent type varies depending on the usage context. - -* Aug 6, 2009 * -* JPEG quality control finalized across processors (although CoreImage applies it in a rather fuzzy-logic way), with tests. - -* Aug 4, 2009 * -* Supports the :aspect/'!' geometry flag in all processors - (thanks to http://www.deepcalm.com/writing/cropped-thumbnails-in-attachment_fu-using-imagescience) -* JPEG quality control on thumbnailing/resizing (still buggy on Rmagick/MiniMagick though). -* Moves from GIF to PNG regardless of the source file extension's case (used to require lowercase) -* Auto-orients image (if EXIF suggests it) prior to processing with RMagickProcessor -* Fixes non-image upload tests (both regular files and Merb files) -* Fixes obsolete failures on RMagick tests (aspect_ratio tested but not initialized anymore due to new callback architecture - -* Apr 17 2008 * -* amazon_s3.yml is now passed through ERB before being passed to AWS::S3 [François Beausoleil] - -* Mar 22 2008 * -* Some tweaks to support Rails 2.0 and Rails 2.1 due to ActiveSupport::Callback changes. - Thanks to http://blog.methodmissing.com/2008/1/19/edge-callback-refactorings-attachment_fu/ - -* Feb. 26, 2008 * -* remove breakpoint from test_helper, makes test suite crazy (at least Rails 2+) [Rob Sanheim] -* make S3 test really optional [Rob Sanheim] - -* Nov 27, 2007 * -* Handle properly ImageScience thumbnails resized from a gif file [Matt Aimonetti] -* Save thumbnails file size properly when using ImageScience [Matt Aimonetti] -* fixed s3 config file loading with latest versions of Rails [Matt Aimonetti] - -* April 2, 2007 * - -* don't copy the #full_filename to the default #temp_paths array if it doesn't exist -* add default ID partitioning for attachments -* add #binmode call to Tempfile (note: ruby should be doing this!) [Eric Beland] -* Check for current type of :thumbnails option. -* allow customization of the S3 configuration file path with the :s3_config_path option. -* Don't try to remove thumbnails if there aren't any. Closes #3 [ben stiglitz] - -* BC * (before changelog) - -* add default #temp_paths entry [mattly] -* add MiniMagick support to attachment_fu [Isacc] -* update #destroy_file to clear out any empty directories too [carlivar] -* fix references to S3Backend module [Hunter Hillegas] -* make #current_data public with db_file and s3 backends [ebryn] -* oops, actually svn add the files for s3 backend. [Jeffrey Hardy] -* experimental s3 support, egad, no tests.... [Jeffrey Hardy] -* doh, fix a few bad references to ActsAsAttachment [sixty4bit] diff --git a/vendor/plugins/pothoven-attachment_fu/Gemfile b/vendor/plugins/pothoven-attachment_fu/Gemfile deleted file mode 100644 index ad69a95..0000000 --- a/vendor/plugins/pothoven-attachment_fu/Gemfile +++ /dev/null @@ -1,13 +0,0 @@ -source 'http://rubygems.org' - - -group :test, :development do - gem 'rails', '~> 3.2' - gem 'sqlite3' - gem 'pothoven-attachment_fu', :path => '.' - gem 'rmagick' - gem 'core_image' - gem 'mini_magick' - gem 'aws-s3', :require => 'aws/s3' - gem 'test-unit' -end diff --git a/vendor/plugins/pothoven-attachment_fu/Gemfile.lock b/vendor/plugins/pothoven-attachment_fu/Gemfile.lock deleted file mode 100644 index 48fbf26..0000000 --- a/vendor/plugins/pothoven-attachment_fu/Gemfile.lock +++ /dev/null @@ -1,109 +0,0 @@ -PATH - remote: . - specs: - pothoven-attachment_fu (3.2.10) - -GEM - remote: http://rubygems.org/ - specs: - actionmailer (3.2.14) - actionpack (= 3.2.14) - mail (~> 2.5.4) - actionpack (3.2.14) - activemodel (= 3.2.14) - activesupport (= 3.2.14) - builder (~> 3.0.0) - erubis (~> 2.7.0) - journey (~> 1.0.4) - rack (~> 1.4.5) - rack-cache (~> 1.2) - rack-test (~> 0.6.1) - sprockets (~> 2.2.1) - activemodel (3.2.14) - activesupport (= 3.2.14) - builder (~> 3.0.0) - activerecord (3.2.14) - activemodel (= 3.2.14) - activesupport (= 3.2.14) - arel (~> 3.0.2) - tzinfo (~> 0.3.29) - activeresource (3.2.14) - activemodel (= 3.2.14) - activesupport (= 3.2.14) - activesupport (3.2.14) - i18n (~> 0.6, >= 0.6.4) - multi_json (~> 1.0) - arel (3.0.2) - aws-s3 (0.6.3) - builder - mime-types - xml-simple - builder (3.0.4) - core_image (0.0.3.5) - erubis (2.7.0) - hike (1.2.3) - i18n (0.6.5) - journey (1.0.4) - json (1.8.0) - mail (2.5.4) - mime-types (~> 1.16) - treetop (~> 1.4.8) - mime-types (1.24) - mini_magick (3.6.0) - subexec (~> 0.2.1) - multi_json (1.7.9) - polyglot (0.3.3) - rack (1.4.5) - rack-cache (1.2) - rack (>= 0.4) - rack-ssl (1.3.3) - rack - rack-test (0.6.2) - rack (>= 1.0) - rails (3.2.14) - actionmailer (= 3.2.14) - actionpack (= 3.2.14) - activerecord (= 3.2.14) - activeresource (= 3.2.14) - activesupport (= 3.2.14) - bundler (~> 1.0) - railties (= 3.2.14) - railties (3.2.14) - actionpack (= 3.2.14) - activesupport (= 3.2.14) - rack-ssl (~> 1.3.2) - rake (>= 0.8.7) - rdoc (~> 3.4) - thor (>= 0.14.6, < 2.0) - rake (10.1.0) - rdoc (3.12.2) - json (~> 1.4) - rmagick (2.13.2) - sprockets (2.2.2) - hike (~> 1.2) - multi_json (~> 1.0) - rack (~> 1.0) - tilt (~> 1.1, != 1.3.0) - sqlite3 (1.3.8) - subexec (0.2.3) - test-unit (2.5.5) - thor (0.18.1) - tilt (1.4.1) - treetop (1.4.15) - polyglot - polyglot (>= 0.3.1) - tzinfo (0.3.37) - xml-simple (1.1.2) - -PLATFORMS - ruby - -DEPENDENCIES - aws-s3 - core_image - mini_magick - pothoven-attachment_fu! - rails (~> 3.2) - rmagick - sqlite3 - test-unit diff --git a/vendor/plugins/pothoven-attachment_fu/LICENSE b/vendor/plugins/pothoven-attachment_fu/LICENSE deleted file mode 100644 index b2d8f02..0000000 --- a/vendor/plugins/pothoven-attachment_fu/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 rick olson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/plugins/pothoven-attachment_fu/README b/vendor/plugins/pothoven-attachment_fu/README deleted file mode 100644 index baa78c2..0000000 --- a/vendor/plugins/pothoven-attachment_fu/README +++ /dev/null @@ -1,193 +0,0 @@ -attachment-fu -============= - -attachment_fu is a plugin by Rick Olson (aka technoweenie ) and is the successor to acts_as_attachment. To get a basic run-through of its capabilities, check out Mike Clark's tutorial . - - -attachment_fu functionality -=========================== - -attachment_fu facilitates file uploads in Ruby on Rails. There are a few storage options for the actual file data, but the plugin always at a minimum stores metadata for each file in the database. - -There are four storage options for files uploaded through attachment_fu: - File system - Database file - Amazon S3 - Rackspace (Mosso) Cloud Files - -Each method of storage many options associated with it that will be covered in the following section. Something to note, however, is that the Amazon S3 storage requires you to modify config/amazon_s3.yml, the Rackspace Cloud Files storage requires you to modify config/rackspace_cloudfiles.yml, and the Database file storage requires an extra table. - - -attachment_fu models -==================== - -For all three of these storage options a table of metadata is required. This table will contain information about the file (hence the 'meta') and its location. This table has no restrictions on naming, unlike the extra table required for database storage, which must have a table name of db_files (and by convention a model of DbFile). - -In the model there are two methods made available by this plugins: has_attachment and validates_as_attachment. - -has_attachment(options = {}) - This method accepts the options in a hash: - :content_type # Allowed content types. - # Allows all by default. Use :image to allow all standard image types. - :min_size # Minimum size allowed. - # 1 byte is the default. - :max_size # Maximum size allowed. - # 1.megabyte is the default. - :size # Range of sizes allowed. - # (1..1.megabyte) is the default. This overrides the :min_size and :max_size options. - :resize_to # Used by RMagick to resize images. - # Pass either an array of width/height, or a geometry string. - :thumbnails # Specifies a set of thumbnails to generate. - # This accepts a hash of filename suffixes and RMagick resizing options. - # This option need only be included if you want thumbnailing. - :thumbnail_class # Set which model class to use for thumbnails. - # This current attachment class is used by default. - :path_prefix # Path to store the uploaded files in. - # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 and Cloud Files backend. - # Setting this sets the :storage to :file_system. - :partition # Whether to partiton files in directories like /0000/0001/image.jpg. Default is true. Only applicable to the :file_system backend. - :storage # Specifies the storage system to use.. - # Defaults to :db_file. Options are :file_system, :db_file, :s3, and :cloud_files. - :cloudfront # If using S3 for storage, this option allows for serving the files via Amazon CloudFront. - # Defaults to false. - :processor # Sets the image processor to use for resizing of the attached image. - # Options include ImageScience, Rmagick, and MiniMagick. Default is whatever is installed. - :uuid_primary_key # If your model's primary key is a 128-bit UUID in hexadecimal format, then set this to true. - :association_options # attachment_fu automatically defines associations with thumbnails with has_many and belongs_to. If there are any additional options that you want to pass to these methods, then specify them here. - - - Examples: - has_attachment :max_size => 1.kilobyte - has_attachment :size => 1.megabyte..2.megabytes - has_attachment :content_type => 'application/pdf' - has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain'] - has_attachment :content_type => :image, :resize_to => [50,50] - has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50' - has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } - has_attachment :storage => :file_system, :path_prefix => 'public/files' - has_attachment :storage => :file_system, :path_prefix => 'public/files', - :content_type => :image, :resize_to => [50,50], :partition => false - has_attachment :storage => :file_system, :path_prefix => 'public/files', - :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } - has_attachment :storage => :s3 - has_attachment :store => :s3, :cloudfront => true - has_attachment :storage => :cloud_files - -validates_as_attachment - This method prevents files outside of the valid range (:min_size to :max_size, or the :size range) from being saved. It does not however, halt the upload of such files. They will be uploaded into memory regardless of size before validation. - - Example: - validates_as_attachment - - -attachment_fu migrations -======================== - -Fields for attachment_fu metadata tables... - in general: - size, :integer # file size in bytes - content_type, :string # mime type, ex: application/mp3 - filename, :string # sanitized filename - that reference images: - height, :integer # in pixels - width, :integer # in pixels - that reference images that will be thumbnailed: - parent_id, :integer # id of parent image (on the same table, a self-referencing foreign-key). - # Only populated if the current object is a thumbnail. - thumbnail, :string # the 'type' of thumbnail this attachment record describes. - # Only populated if the current object is a thumbnail. - # Usage: - # [ In Model 'Avatar' ] - # has_attachment :content_type => :image, - # :storage => :file_system, - # :max_size => 500.kilobytes, - # :resize_to => '320x200>', - # :thumbnails => { :small => '10x10>', - # :thumb => '100x100>' } - # [ Elsewhere ] - # @user.avatar.thumbnails.first.thumbnail #=> 'small' - that reference files stored in the database (:db_file): - db_file_id, :integer # id of the file in the database (foreign key) - -Field for attachment_fu db_files table: - data, :binary # binary file data, for use in database file storage - - -attachment_fu views -=================== - -There are two main views tasks that will be directly affected by attachment_fu: upload forms and displaying uploaded images. - -There are two parts of the upload form that differ from typical usage. - 1. Include ':multipart => true' in the html options of the form_for tag. - Example: - <% form_for(:attachment_metadata, :url => { :action => "create" }, :html => { :multipart => true }) do |form| %> - - 2. Use the file_field helper with :uploaded_data as the field name. - Example: - <%= form.file_field :uploaded_data %> - -Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system, s3, and Cloud Files storage. - -public_filename(thumbnail = nil) - Returns the public path to the file. If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail. - Examples: - attachment_obj.public_filename #=> /attachments/2/file.jpg - attachment_obj.public_filename(:thumb) #=> /attachments/2/file_thumb.jpg - attachment_obj.public_filename(:small) #=> /attachments/2/file_small.jpg - -When serving files from database storage, doing more than simply downloading the file is beyond the scope of this document. - - -attachment_fu controllers -========================= - -There are two considerations to take into account when using attachment_fu in controllers. - -The first is when the files have no publicly accessible path and need to be downloaded through an action. - -Example: - def readme - send_file '/path/to/readme.txt', :type => 'plain/text', :disposition => 'inline' - end - -See the possible values for send_file for reference. - - -The second is when saving the file when submitted from a form. -Example in view: - <%= form.file_field :attachable, :uploaded_data %> - -Example in controller: - def create - @attachable_file = AttachmentMetadataModel.new(params[:attachable]) - if @attachable_file.save - flash[:notice] = 'Attachment was successfully created.' - redirect_to attachable_url(@attachable_file) - else - render :action => :new - end - end - -attachement_fu scripting -==================================== - -You may wish to import a large number of images or attachments. -The following example shows how to upload a file from a script. - -#!/usr/bin/env ./script/runner - -# required to use ActionController::TestUploadedFile -require 'action_controller' -require 'action_controller/test_process.rb' - -path = "./public/images/x.jpg" - -# mimetype is a string like "image/jpeg". One way to get the mimetype for a given file on a UNIX system -# mimetype = `file -ib #{path}`.gsub(/\n/,"") - -mimetype = "image/jpeg" - -# This will "upload" the file at path and create the new model. -@attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype)) -@attachable.save diff --git a/vendor/plugins/pothoven-attachment_fu/README.rdoc b/vendor/plugins/pothoven-attachment_fu/README.rdoc deleted file mode 100644 index 35578ee..0000000 --- a/vendor/plugins/pothoven-attachment_fu/README.rdoc +++ /dev/null @@ -1,352 +0,0 @@ -= attachment-fu - -attachment_fu is a plugin by Rick Olson (aka technoweenie -http://techno-weenie.net) and is the successor to acts_as_attachment. To get a -basic run-through of its capabilities, check out {Mike Clark's -tutorial}[http://clarkware.com/cgi/blosxom/2007/02/24#FileUploadFu]. - -= attachment_fu functionality - -attachment_fu facilitates file uploads in Ruby on Rails. There are a few -storage options for the actual file data, but the plugin always at a minimum -stores metadata for each file in the database. - -There are four storage options for files uploaded through attachment_fu: - -* File system -* Database file -* Amazon S3 -* Rackspace (Mosso) Cloud Files - -Each method of storage many options associated with it that will be covered in -the following section. Something to note, however, is that the Amazon S3 storage -requires you to modify +config/amazon_s3.yml+, the Rackspace Cloud Files storage -requires you to modify +config/rackspace_cloudfiles.yml+, and the Database file -storage requires an extra table. - -= attachment_fu models - -For all three of these storage options a table of metadata is required. This -table will contain information about the file (hence the 'meta') and its -location. This table has no restrictions on naming, unlike the extra table -required for database storage, which must have a table name of +db_files+ (and -by convention a model of +DbFile+). - -Two methods are available to models: +has_attachment+ and -+validates_as_attachment+. - -== has_attachment(options = {}) - -This method accepts the options in a hash: - -[:content_type] - Allowed content types. - - By default, all content types are allowed. Use +:image+ to allow all - standard image types. - -[:min_size] - Minimum file size. - - By default, set to +1.byte+. - -[:max_size] - Maximum file size. - - By default, set to +1.megabyte+. - -[:size] - Minimum and maximum file size. - - By default, set to +1..1.megabyte+. Overrides +:min_size+ and - +:max_size+. - -[:resize_to] - Used by RMagick. - - Tells RMagick how to resize images. Pass either an array specifying - width and height or a geometry string. Prefixing the geometry string - with a 'c' will crop the image to the specified size. - -[:sharpen_on_resize] - Used by RMagick. - - If set to true, images are sharpened after being resized. - -[:thumbnails] - A set of thumbnails to generate. - - This accepts a hash of filename suffixes and RMagick resizing options. This - option need only be included if you want thumbnailing. - - If you have a polymorphic parent relationship, you can provide - parent-type-specific thumbnail settings by using a pair with the type string - as key and a Hash of thumbnail definitions, or a method symbol, as value. - The method symbol will call the named method in order to get a - dynamically-built Hash of thumbnail definitions, which gives you full - flexibility. AttachmentFu automatically detects your first polymorphic - +belongs_to+ relationship. - -[:thumbnail_class] - Which model class to use for thumbnails. - - By default, the current attachment class is used. - -[:jpeg_quality] - JPEG quality settings for thumbnail resizes. - - Arguments can be in multiple formats: - - * Integer from 0 (basically crap) to 100 (basically lossless, fat files). - - * When relying on tdd-image_science, you can also use one of its +JPEG_xxx+ - constants for predefined ratios/settings. - - * You can also use a Hash, with keys being either thumbnail symbols (I - repeat: _symbols_) or surface boundaries. A surface boundary is a string - starting with either '<' or '>=', followed by a number of pixels. This - lets you specify per-thumbnail or per-general-thumbnail-"size" JPEG - qualities. (which can be useful when you have a _lot_ of thumbnail - options). Surface example: {'<2000' => 90, '>=2000' => 75}. - - Defaults vary depending on the processor (ImageScience: 100%, - Rmagick/MiniMagick/Gd2: 75%, CoreImage: auto-adjust). Note that only - tdd-image_science (available from GitHub) currently supports explicit JPEG - quality; the default image_science currently forces 100%. - -[:path_prefix] - Path to store the uploaded files in. Uses public/#{table_name} - by default for the filesystem, and just #{table_name} for the - S3 and Cloud Files backend. Setting this sets the +:storage+ to - +:file_system+. - -[:partition] - Whether to partiton files in directories like +/0000/0001/image.jpg+. - Default is true. Only applicable to the +:file_system+ backend. - -[:storage] - Specifies the storage system to use. Defaults to +:db_file+. Options are - +:file_system+, +:db_file+, +:s3+, and +:cloud_files+. - -[:cloudfront] - If using S3 for storage, this option allows for serving the files via Amazon - CloudFront. Defaults to false. - -[:processor] - Sets the image processor to use for resizing of the attached image. Options - include ImageScience, Rmagick, MiniMagick, Gd2 and CoreImage. Default is - whatever is installed. - -[:uuid_primary_key] - If your model's primary key is a 128-bit UUID in hexadecimal format, then - set this to true. - -[:association_options] - attachment_fu automatically defines associations with thumbnails with - +has_many+ and +belongs_to+. If there are any additional options that you - want to pass to these methods, then specify them here. - -Examples: - - has_attachment(content_type: 'application/pdf') - has_attachment( - content_type: ['application/pdf', 'application/msword', 'text/plain'] - ) - has_attachment(content_type: ['application/pdf', :image], resize_to: 'x50') - has_attachment(content_type: :image, resize_to: [50,50]) - has_attachment(max_size: 1.kilobyte) - has_attachment(size: 1.megabyte..2.megabytes) - has_attachment(storage: :cloud_files) - has_attachment(storage: :file_system, path_prefix: 'public/files') - has_attachment( - storage: :file_system, - path_prefix: 'public/files', - content_type: :image, - resize_to: [50, 50], - partition: false - ) - has_attachment( - storage: :file_system, - path_prefix: 'public/files', - thumbnails: {thumb: [50, 50], geometry: 'x50'} - ) - has_attachment(storage: :s3) - has_attachment(store: :s3, cloudfront: true) - has_attachment(thumbnails: {thumb: [50, 50], geometry: 'x50'}) - - # Let's say we have a polymorphic belongs_to, e.g. called 'imageable', where - # imageable_type (or whatever the :foreign_type option was set to) can be, - # among other things, 'Product', 'User' or 'Editorial', each of which should - # have extra thumbnails: - - has_attachment(thumbnails: { - editorials: {fullsize: '150x100>'}, - geometry: 'x50', - products: {large_thumb: '169x169!', zoomed: '500x500>'}, - thumb: [50, 50], - users: {avatar: '64x64!'} - }) - - # JPEG qualities… - - has_attachment(jpeg_quality: 75) - has_attachment(jpeg_quality: 80 | ImageScience::JPEG_PROGRESSIVE) - has_attachment( - thumbnails: {thumb: [50, 50], geometry: 'x50'}, - jpeg_quality: {'<2000' => 90, '>=2000' => 75} - ) - has_attachment( - thumbnails: {thumb: [50, 50], geometry: 'x50'}, - jpeg_quality: {nil => 75, thumb: 90, geometry: 90} - ) - -== validates_as_attachment - -This method prevents files outside of the valid range (+:min_size+ to -+:max_size+, or the +:size+ range) from being saved. It does not however, halt -the upload of such files. They will be uploaded into memory regardless of size -before validation. - -To perform this validation, simply add +validates_as_attachment+ to your model. - -= attachment_fu migrations - -Fields for attachment_fu metadata tables… - -In general: - - size, :integer # file size in bytes - content_type, :string # mime type, ex: application/mp3 - filename, :string # sanitized filename - -That reference images: - - height, :integer # in pixels - width, :integer # in pixels - -That reference images that will be thumbnailed: - - parent_id, :integer # id of parent image (on the same table, a - # self-referencing foreign-key). Only populated if - # the current object is a thumbnail. - thumbnail, :string # The type of thumbnail this attachment record - # describes. Only populated if the current object is - # a thumbnail. Example: - # - # (In Model 'Avatar') - # has_attachment( - # :content_type => :image, - # :storage => :file_system, - # :max_size => 500.kilobytes, - # :resize_to => '320x200>', - # :thumbnails => { - # :small => '10x10>', - # :thumb => '100x100>' - # } - # ) - # - # (Elsewhere) - # @user.avatar.thumbnails.first.thumbnail # => 'small' - # - db_file_id, :integer # ID of the file in the database (foreign key) that - # reference files stored in the database (:db_file). - -Field for attachment_fu +db_files+ table: - - data, :binary # binary file data, for use in database file storage - -= attachment_fu views - -There are two main views tasks that will be directly affected by attachment_fu: -upload forms and displaying uploaded images. - -There are two parts of the upload form that differ from typical usage. - -1. Include multipart: true in the html options of the +form_for+ - tag. Example: - - <%= - form_for( - :attachment_metadata, - url: {action: "create"}, - html: {multipart: true} - ) do |form| - %> - -2. Use the +file_field+ helper with +:uploaded_data+ as the field name. Example: - - <%= form.file_field(:uploaded_data) %> - -Displaying uploaded images is made easy by the +public_filename+ method of the -ActiveRecord attachment objects using file system, s3, and Cloud Files storage. - -== public_filename(thumbnail = nil) - -Returns the public path to the file. If a thumbnail prefix is specified it will -return the public file path to the corresponding thumbnail. Examples: - - attachment_obj.public_filename #=> /attachments/2/file.jpg - attachment_obj.public_filename(:thumb) #=> /attachments/2/file_thumb.jpg - attachment_obj.public_filename(:small) #=> /attachments/2/file_small.jpg - -When serving files from database storage, doing more than simply downloading the -file is beyond the scope of this document. - -= attachment_fu controllers - -There are two considerations to take into account when using attachment_fu in -controllers. - -The first is when the files have no publicly accessible path and need to be -downloaded through an action. Example: - - def readme - send_file( - '/path/to/readme.txt', - type: 'plain/text', - disposition: 'inline' - ) - end - -See the possible values for +send_file+ for reference. - -The second is when saving the file when submitted from a form. Example: - -In a view: - - <%= form.file_field(:attachable, :uploaded_data) %> - -In a controller: - - def create - @attachable_file = AttachmentMetadataModel.new(params[:attachable]) - if @attachable_file.save - flash[:notice] = 'Attachment was successfully created.' - redirect_to(attachable_url(@attachable_file)) - else - redirect_to(action: 'new') - end - end - -= attachment_fu scripting - -You may wish to import a large number of images or attachments. The following -example shows how to upload a file from a script. - - #!/usr/bin/env ./script/runner - - # required to use ActionController::TestUploadedFile - require 'action_controller' - require 'action_controller/test_process.rb' - - path = "./public/images/x.jpg" - - # `mimetype` is a string like "image/jpeg". One way to get the mimetype for - # a given file on a UNIX system: mimetype = `file -ib #{path}`.gsub(/\n/,"") - mimetype = "image/jpeg" - - # This will "upload" the file at path and create the new model. - @attachable = AttachmentMetadataModel.new( - uploaded_data: ActionController::TestUploadedFile.new(path, mimetype) - ) - @attachable.save diff --git a/vendor/plugins/pothoven-attachment_fu/Rakefile b/vendor/plugins/pothoven-attachment_fu/Rakefile deleted file mode 100644 index f90a073..0000000 --- a/vendor/plugins/pothoven-attachment_fu/Rakefile +++ /dev/null @@ -1,22 +0,0 @@ -require 'rake' -require 'rake/testtask' -require 'rdoc/task' - -desc 'Default: run unit tests.' -task :default => :test - -desc 'Test the attachment_fu plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the attachment_fu plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'ActsAsAttachment' - rdoc.options << '--line-numbers --inline-source' - rdoc.rdoc_files.include('README.rdoc') - rdoc.rdoc_files.include('lib/**/*.rb') -end diff --git a/vendor/plugins/pothoven-attachment_fu/amazon_s3.yml.tpl b/vendor/plugins/pothoven-attachment_fu/amazon_s3.yml.tpl deleted file mode 100644 index 5c585e7..0000000 --- a/vendor/plugins/pothoven-attachment_fu/amazon_s3.yml.tpl +++ /dev/null @@ -1,17 +0,0 @@ -development: - bucket_name: appname_development - access_key_id: - secret_access_key: - distribution_domain: XXXX.cloudfront.net - -test: - bucket_name: appname_test - access_key_id: - secret_access_key: - distribution_domain: XXXX.cloudfront.net - -production: - bucket_name: appname - access_key_id: - secret_access_key: - distribution_domain: XXXX.cloudfront.net diff --git a/vendor/plugins/pothoven-attachment_fu/attachment_fu.gemspec b/vendor/plugins/pothoven-attachment_fu/attachment_fu.gemspec deleted file mode 100644 index 9cbcfd0..0000000 --- a/vendor/plugins/pothoven-attachment_fu/attachment_fu.gemspec +++ /dev/null @@ -1,23 +0,0 @@ -# -*- encoding: utf-8 -*- - -Gem::Specification.new do |s| - s.name = %q{pothoven-attachment_fu} - s.authors = ["Rick Olson", "Steven Pothoven"] - s.summary = %q{attachment_fu as a gem} - s.description = %q{This is a fork of Rick Olson's attachment_fu adding Ruby 1.9 and Rails 3.2 support as well as some other enhancements.} - s.email = %q{steven@pothoven.net} - s.homepage = %q{http://github.com/pothoven/attachment_fu} - s.version = "3.2.10" - s.date = %q{2013-08-22} - - s.files = Dir.glob("{lib,vendor}/**/*") + %w( CHANGELOG LICENSE README.rdoc amazon_s3.yml.tpl rackspace_cloudfiles.yml.tpl ) - s.extra_rdoc_files = ["README.rdoc"] - s.rdoc_options = ["--inline-source", "--charset=UTF-8"] - s.require_paths = ["lib"] - s.rubyforge_project = "nowarning" - s.rubygems_version = %q{1.3.5} - - if s.respond_to? :specification_version then - s.specification_version = 2 - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/config/database.yml b/vendor/plugins/pothoven-attachment_fu/config/database.yml deleted file mode 100644 index 2cfeb7a..0000000 --- a/vendor/plugins/pothoven-attachment_fu/config/database.yml +++ /dev/null @@ -1,3 +0,0 @@ -test: - adapter: sqlite3 - database: ":memory:" diff --git a/vendor/plugins/pothoven-attachment_fu/config/environment.rb b/vendor/plugins/pothoven-attachment_fu/config/environment.rb deleted file mode 100644 index e69de29..0000000 --- a/vendor/plugins/pothoven-attachment_fu/config/environment.rb +++ /dev/null diff --git a/vendor/plugins/pothoven-attachment_fu/init.rb b/vendor/plugins/pothoven-attachment_fu/init.rb deleted file mode 100644 index c377063..0000000 --- a/vendor/plugins/pothoven-attachment_fu/init.rb +++ /dev/null @@ -1,6 +0,0 @@ -require 'geometry' -ActiveRecord::Base.send(:extend, Technoweenie::AttachmentFu::ActMethods) -Technoweenie::AttachmentFu.tempfile_path = ATTACHMENT_FU_TEMPFILE_PATH if Object.const_defined?(:ATTACHMENT_FU_TEMPFILE_PATH) -FileUtils.mkdir_p Technoweenie::AttachmentFu.tempfile_path - -$:.unshift(File.dirname(__FILE__) + '/vendor') diff --git a/vendor/plugins/pothoven-attachment_fu/install.rb b/vendor/plugins/pothoven-attachment_fu/install.rb deleted file mode 100644 index 1b75ff8..0000000 --- a/vendor/plugins/pothoven-attachment_fu/install.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'fileutils' - -s3_config = File.dirname(__FILE__) + '/../../../config/amazon_s3.yml' -FileUtils.cp File.dirname(__FILE__) + '/amazon_s3.yml.tpl', s3_config unless File.exist?(s3_config) -cloudfiles_config = File.dirname(__FILE__) + '/../../../config/rackspace_cloudfiles.yml' -FileUtils.cp File.dirname(__FILE__) + '/rackspace_cloudfiles.yml.tpl', cloudfiles_config unless File.exist?(cloudfiles_config) -puts IO.read(File.join(File.dirname(__FILE__), 'README.rdoc')) diff --git a/vendor/plugins/pothoven-attachment_fu/lib/geometry.rb b/vendor/plugins/pothoven-attachment_fu/lib/geometry.rb deleted file mode 100644 index 1f1c2fa..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/geometry.rb +++ /dev/null @@ -1,96 +0,0 @@ -# This Geometry class was yanked from RMagick. However, it lets ImageMagick handle the actual change_geometry. -# Use #new_dimensions_for to get new dimensions -# Used so I can use spiffy RMagick geometry strings with ImageScience -class Geometry - # @ is removed until support for them is added - FLAGS = ['', '%', '<', '>', '!']#, '@'] - RFLAGS = { '%' => :percent, - '!' => :aspect, - '<' => :>, - '>' => :<, - '@' => :area } - - attr_accessor :width, :height, :x, :y, :flag - - def initialize(width=nil, height=nil, x=nil, y=nil, flag=nil) - # Support floating-point width and height arguments so Geometry - # objects can be used to specify Image#density= arguments. - raise ArgumentError, "width must be >= 0: #{width}" if width < 0 - raise ArgumentError, "height must be >= 0: #{height}" if height < 0 - @width = width.to_f - @height = height.to_f - @x = x.to_i - @y = y.to_i - @flag = flag - end - - # Construct an object from a geometry string - RE = /\A(\d*)(?:x(\d+)?)?([-+]\d+)?([-+]\d+)?([%!<>@]?)\Z/ - - def self.from_s(str) - raise(ArgumentError, "no geometry string specified") unless str - - if m = RE.match(str) - new(m[1].to_i, m[2].to_i, m[3].to_i, m[4].to_i, RFLAGS[m[5]]) - else - raise ArgumentError, "invalid geometry format" - end - end - - # Convert object to a geometry string - def to_s - str = '' - str << "%g" % @width if @width > 0 - str << 'x' if (@width > 0 || @height > 0) - str << "%g" % @height if @height > 0 - str << "%+d%+d" % [@x, @y] if (@x != 0 || @y != 0) - str << FLAGS[@flag.to_i] - end - - # attempts to get new dimensions for the current geometry string given these old dimensions. - # This doesn't implement the aspect flag (!) or the area flag (@). PDI - def new_dimensions_for(orig_width, orig_height) - new_width = orig_width - new_height = orig_height - - case @flag - when :percent - scale_x = @width.zero? ? 100 : @width - scale_y = @height.zero? ? @width : @height - new_width = scale_x.to_f * (orig_width.to_f / 100.0) - new_height = scale_y.to_f * (orig_height.to_f / 100.0) - when :aspect - new_width = @width unless @width.nil? - new_height = @height unless @height.nil? - when :<, :>, nil - scale_factor = - if new_width.zero? || new_height.zero? - 1.0 - else - if @width.nonzero? && @height.nonzero? - [@width.to_f / new_width.to_f, @height.to_f / new_height.to_f].min - else - @width.nonzero? ? (@width.to_f / new_width.to_f) : (@height.to_f / new_height.to_f) - end - end - new_width = scale_factor * new_width.to_f - new_height = scale_factor * new_height.to_f - new_width = orig_width if @flag && orig_width.send(@flag, new_width) - new_height = orig_height if @flag && orig_height.send(@flag, new_height) - end - - [new_width, new_height].collect! { |v| [v.round, 1].max } - end -end - -class Array - # allows you to get new dimensions for the current array of dimensions with a given geometry string - # - # [50, 64] / '40>' # => [40, 51] - def /(geometry) - raise ArgumentError, "Only works with a [width, height] pair" if size != 2 - raise ArgumentError, "Must pass a valid geometry string or object" unless geometry.is_a?(String) || geometry.is_a?(Geometry) - geometry = Geometry.from_s(geometry) if geometry.is_a?(String) - geometry.new_dimensions_for first, last - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/lib/pothoven-attachment_fu.rb b/vendor/plugins/pothoven-attachment_fu/lib/pothoven-attachment_fu.rb deleted file mode 100644 index adb1e62..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/pothoven-attachment_fu.rb +++ /dev/null @@ -1,12 +0,0 @@ -class Engine < Rails::Engine - # Mimic old vendored plugin behavior, attachment_fu/lib is autoloaded. - config.autoload_paths << File.expand_path("..", __FILE__) - - initializer "attachment_fu" do - require 'geometry' - - ActiveRecord::Base.send(:extend, Technoweenie::AttachmentFu::ActMethods) - Technoweenie::AttachmentFu.tempfile_path = ATTACHMENT_FU_TEMPFILE_PATH if Object.const_defined?(:ATTACHMENT_FU_TEMPFILE_PATH) - FileUtils.mkdir_p Technoweenie::AttachmentFu.tempfile_path - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu.rb deleted file mode 100644 index d9a8492..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu.rb +++ /dev/null @@ -1,588 +0,0 @@ -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - @@default_processors = %w(ImageScience Rmagick MiniMagick Gd2 CoreImage) - @@tempfile_path = File.join(Rails.root, 'tmp', 'attachment_fu') - @@content_types = [ - 'image/jpeg', - 'image/pjpeg', - 'image/jpg', - 'image/gif', - 'image/png', - 'image/x-png', - 'image/jpg', - 'image/x-ms-bmp', - 'image/bmp', - 'image/x-bmp', - 'image/x-bitmap', - 'image/x-xbitmap', - 'image/x-win-bitmap', - 'image/x-windows-bmp', - 'image/ms-bmp', - 'application/bmp', - 'application/x-bmp', - 'application/x-win-bitmap', - 'application/preview', - 'image/jp_', - 'application/jpg', - 'application/x-jpg', - 'image/pipeg', - 'image/vnd.swiftview-jpeg', - 'image/x-xbitmap', - 'application/png', - 'application/x-png', - 'image/gi_', - 'image/x-citrix-pjpeg' - ] - mattr_reader :content_types, :tempfile_path, :default_processors - mattr_writer :tempfile_path - - class ThumbnailError < StandardError; end - class AttachmentError < StandardError; end - - module ActMethods - # Options: - # * :content_type - Allowed content types. Allows all by default. Use :image to allow all standard image types. - # * :min_size - Minimum size allowed. 1 byte is the default. - # * :max_size - Maximum size allowed. 1.megabyte is the default. - # * :size - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options. - # * :resize_to - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string. Prefix geometry string with 'c' to crop image, ex. 'c100x100' - # * :sharpen_on_resize - When using RMagick, setting to true will sharpen images after resizing. - # * :jpeg_quality - Used to provide explicit JPEG quality for thumbnail/resize saves. Can have multiple formats: - # * Integer from 0 (basically crap) to 100 (basically lossless, fat files). - # * When relying on ImageScience, you can also use one of its +JPEG_xxx+ constants for predefined ratios/settings. - # * You can also use a Hash, with keys being either thumbnail symbols (I repeat: _symbols_) or surface boundaries. - # A surface boundary is a string starting with either '<' or '>=', followed by a number of pixels. This lets you - # specify per-thumbnail or per-general-thumbnail-"size" JPEG qualities. (which can be useful when you have a - # _lot_ of thumbnail options). Surface example: +{ '<2000' => 90, '>=2000' => 75 }+. - # Defaults vary depending on the processor (ImageScience: 100%, Rmagick/MiniMagick/Gd2: 75%, - # CoreImage: auto-adjust). Note that only tdd-image_science (available from GitHub) currently supports explicit JPEG quality; - # the default image_science currently forces 100%. - # * :thumbnails - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and - # RMagick resizing options. If you have a polymorphic parent relationship, you can provide parent-type-specific - # thumbnail settings by using a pair with the type string as key and a Hash of thumbnail definitions as value. - # AttachmentFu automatically detects your first polymorphic +belongs_to+ relationship. - # * :thumbnail_class - Set what class to use for thumbnails. This attachment class is used by default. - # * :path_prefix - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name} - # for the S3 backend. Setting this sets the :storage to :file_system. - - # * :storage - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system. - # * :cloundfront - Set to true if you are using S3 storage and want to serve the files through CloudFront. You will need to - # set a distribution domain in the amazon_s3.yml config file. Defaults to false - # * :bucket_key - Use this to specify a different bucket key other than :bucket_name in the amazon_s3.yml file. This allows you to use - # different buckets for different models. An example setting would be :image_bucket and the you would need to define the name of the corresponding - # bucket in the amazon_s3.yml file. - - # * :keep_profile By default image EXIF data will be stripped to minimize image size. For small thumbnails this proivides important savings. Picture quality is not affected. Set to false if you want to keep the image profile as is. ImageScience will allways keep EXIF data. - # - # Examples: - # has_attachment :max_size => 1.kilobyte - # has_attachment :size => 1.megabyte..2.megabytes - # has_attachment :content_type => 'application/pdf' - # has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain'] - # has_attachment :content_type => :image, :resize_to => [50,50] - # has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50' - # has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } - # has_attachment :storage => :file_system, :path_prefix => 'public/files' - # has_attachment :storage => :file_system, :path_prefix => 'public/files', - # :content_type => :image, :resize_to => [50,50] - # has_attachment :storage => :file_system, :path_prefix => 'public/files', - # :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } - # has_attachment :storage => :s3 - def has_attachment(options = {}) - # this allows you to redefine the acts' options for each subclass, however - options[:min_size] ||= 1 - options[:max_size] ||= 1.megabyte - options[:size] ||= (options[:min_size]..options[:max_size]) - options[:thumbnails] ||= {} - options[:thumbnail_class] ||= self - options[:s3_access] ||= :public_read - options[:cloudfront] ||= false - options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? ::Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil? - options[:cache_control] ||= "max-age=315360000" # 10 years - - unless options[:thumbnails].is_a?(Hash) - raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }" - end - - extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods) - include InstanceMethods unless included_modules.include?(InstanceMethods) - - parent_options = attachment_options || {} - # doing these shenanigans so that #attachment_options is available to processors and backends - self.attachment_options = options - - attr_accessor :thumbnail_resize_options - - attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file - attachment_options[:storage] ||= parent_options[:storage] - attachment_options[:path_prefix] ||= attachment_options[:file_system_path] - if attachment_options[:path_prefix].nil? - attachment_options[:path_prefix] = case attachment_options[:storage] - when :s3 then table_name - when :cloud_files then table_name - else File.join("public", table_name) - end - end - attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/' - - association_options = { :foreign_key => 'parent_id' } - if attachment_options[:association_options] - association_options.merge!(attachment_options[:association_options]) - end - with_options(association_options) do |m| - m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}" - m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty? - end - - storage_mod = ::Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend") - include storage_mod unless included_modules.include?(storage_mod) - - case attachment_options[:processor] - when :none, nil - processors = ::Technoweenie::AttachmentFu.default_processors.dup - begin - if processors.any? - attachment_options[:processor] = processors.first - processor_mod = ::Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor") - include processor_mod unless included_modules.include?(processor_mod) - end - rescue Object, Exception - raise unless load_related_exception?($!) - - processors.shift - retry - end - else - begin - processor_mod = ::Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor") - include processor_mod unless included_modules.include?(processor_mod) - rescue Object, Exception - raise unless load_related_exception?($!) - - puts "Problems loading #{options[:processor]}Processor: #{$!}" - end - end unless parent_options[:processor] # Don't let child override processor - end - - def load_related_exception?(e) #:nodoc: implementation specific - case - when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError" - # We can't rescue CompilationError directly, as it is part of the RubyInline library. - # We must instead rescue RuntimeError, and check the class' name. - true - else - false - end - end - private :load_related_exception? - end - - module ClassMethods - delegate :content_types, :to => ::Technoweenie::AttachmentFu - - # Performs common validations for attachment models. - def validates_as_attachment - validates_presence_of :size, :content_type, :filename - validate :attachment_attributes_valid? - end - - # Returns true or false if the given content type is recognized as an image. - def image?(content_type) - content_types.include?(content_type) - end - - def self.extended(base) - base.class_attribute :attachment_options - base.before_destroy :destroy_thumbnails - base.before_validation :set_size_from_temp_path - base.after_destroy :destroy_file - base.after_validation :process_attachment - base.after_save :after_process_attachment - #if defined?(::ActiveSupport::Callbacks) - # base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved - #end - end - - unless defined?(::ActiveSupport::Callbacks) - # Callback after an image has been resized. - # - # class Foo < ActiveRecord::Base - # acts_as_attachment - # after_resize do |record, img| - # record.aspect_ratio = img.columns.to_f / img.rows.to_f - # end - # end - def after_resize(&block) - write_inheritable_array(:after_resize, [block]) - end - - # Callback after an attachment has been saved either to the file system or the DB. - # Only called if the file has been changed, not necessarily if the record is updated. - # - # class Foo < ActiveRecord::Base - # acts_as_attachment - # after_attachment_saved do |record| - # ... - # end - # end - def after_attachment_saved(&block) - write_inheritable_array(:after_attachment_saved, [block]) - end - - # Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required. - # - # class Foo < ActiveRecord::Base - # acts_as_attachment - # before_thumbnail_saved do |thumbnail| - # record = thumbnail.parent - # ... - # end - # end - def before_thumbnail_saved(&block) - write_inheritable_array(:before_thumbnail_saved, [block]) - end - end - - # Get the thumbnail class, which is the current attachment class by default. - # Configure this with the :thumbnail_class option. - def thumbnail_class - attachment_options[:thumbnail_class] = attachment_options[:thumbnail_class].constantize unless attachment_options[:thumbnail_class].is_a?(Class) - attachment_options[:thumbnail_class] - end - - # Copies the given file path to a new tempfile, returning the closed tempfile. - def copy_to_temp_file(file, temp_base_name) - Tempfile.new(temp_base_name, ::Technoweenie::AttachmentFu.tempfile_path).tap do |tmp| - tmp.close - FileUtils.cp file, tmp.path - end - end - - # Writes the given data to a new tempfile, returning the closed tempfile. - def write_to_temp_file(data, temp_base_name) - Tempfile.new(temp_base_name, ::Technoweenie::AttachmentFu.tempfile_path).tap do |tmp| - tmp.binmode - tmp.write data - tmp.close - end - end - - def polymorphic_relation_type_column - return @@_polymorphic_relation_type_column if defined?(@@_polymorphic_relation_type_column) - # Checked against ActiveRecord 1.15.6 through Edge @ 2009-08-05. - ref = reflections.values.detect { |r| r.macro == :belongs_to && r.options[:polymorphic] } - @@_polymorphic_relation_type_column = ref && ref.options[:foreign_type] - end - end - - module InstanceMethods - def self.included(base) - base.define_callbacks *[:after_resize, :after_attachment_saved, :before_thumbnail_saved] if base.respond_to?(:define_callbacks) - end - - # Checks whether the attachment's content type is an image content type - def image? - self.class.image?(content_type) - end - - # Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute. - def thumbnailable? - image? && respond_to?(:parent_id) && parent_id.nil? - end - - # Returns the class used to create new thumbnails for this attachment. - def thumbnail_class - self.class.thumbnail_class - end - - # Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg' - def thumbnail_name_for(thumbnail = nil) - if thumbnail.blank? - if filename.nil? - return '' - else - return filename - end - end - - ext = nil - basename = filename.gsub /\.\w+$/ do |s| - ext = s; '' - end - # ImageScience doesn't create gif thumbnails, only pngs - ext.sub!(/gif$/i, 'png') if attachment_options[:processor] == "ImageScience" - "#{basename}_#{thumbnail}#{ext}" - end - - # Creates or updates the thumbnail for the current attachment. - def create_or_update_thumbnail(temp_file, file_name_suffix, *size) - thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column")) - find_or_initialize_thumbnail(file_name_suffix).tap do |thumb| - thumb.temp_paths.unshift temp_file - thumb.send(:assign_attributes, { - :content_type => content_type, - :filename => thumbnail_name_for(file_name_suffix), - :thumbnail_resize_options => size - }, :without_protection => true) - callback_with_args :before_thumbnail_saved, thumb - thumb.save! - end - end - - # Sets the content type. - def content_type=(new_type) - write_attribute :content_type, new_type.to_s.strip - end - - # Sanitizes a filename. - def filename=(new_name) - write_attribute :filename, sanitize_filename(new_name) - end - - # Returns the width/height in a suitable format for the image_tag helper: (100x100) - def image_size - [width.to_s, height.to_s] * 'x' - end - - # Returns true if the attachment data will be written to the storage system on the next save - def save_attachment? - File.file?(temp_path.class == String ? temp_path : temp_path.to_filename) - end - - # nil placeholder in case this field is used in a form. - def uploaded_data() nil; end - - # This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need - # any special code in your controller. - # - # <% form_for :attachment, :html => { :multipart => true } do |f| -%> - #

<%= f.file_field :uploaded_data %>

- #

<%= submit_tag :Save %> - # <% end -%> - # - # @attachment = Attachment.create! params[:attachment] - # - # TODO: Allow it to work with Merb tempfiles too. - def uploaded_data=(file_data) - if file_data.respond_to?(:content_type) - return nil if file_data.size == 0 - self.content_type = file_data.content_type - self.filename = file_data.original_filename if respond_to?(:filename) - else - return nil if file_data.blank? || file_data['size'] == 0 - self.content_type = file_data['content_type'] - self.filename = file_data['filename'] - file_data = file_data['tempfile'] - end - if file_data.is_a?(StringIO) - file_data.rewind - set_temp_data file_data.read - else - file_data.respond_to?(:tempfile) ? self.temp_paths.unshift( file_data.tempfile.path ) : self.temp_paths.unshift( file_data.path ) - end - end - - # Gets the latest temp path from the collection of temp paths. While working with an attachment, - # multiple Tempfile objects may be created for various processing purposes (resizing, for example). - # An array of all the tempfile objects is stored so that the Tempfile instance is held on to until - # it's not needed anymore. The collection is cleared after saving the attachment. - def temp_path - p = temp_paths.first - p.respond_to?(:path) ? p.path : p.to_s - end - - # Gets an array of the currently used temp paths. Defaults to a copy of #full_filename. - def temp_paths - @temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ? - [] : [copy_to_temp_file(full_filename)]) - end - - # Gets the data from the latest temp file. This will read the file into memory. - def temp_data - save_attachment? ? File.read(temp_path) : nil - end - - # Writes the given data to a Tempfile and adds it to the collection of temp files. - def set_temp_data(data) - temp_paths.unshift write_to_temp_file data unless data.nil? - end - - # Copies the given file to a randomly named Tempfile. - def copy_to_temp_file(file) - self.class.copy_to_temp_file file, random_tempfile_filename - end - - # Writes the given file to a randomly named Tempfile. - def write_to_temp_file(data) - self.class.write_to_temp_file data, random_tempfile_filename - end - - # Stub for creating a temp file from the attachment data. This should be defined in the backend module. - def create_temp_file() end - - # Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block. - # - # @attachment.with_image do |img| - # self.data = img.thumbnail(100, 100).to_blob - # end - # - def with_image(&block) - self.class.with_image(temp_path, &block) - end - - protected - # Generates a unique filename for a Tempfile. - def random_tempfile_filename - base_filename = filename ? filename.gsub(/\.\w+$/, '') : 'attachment' - ext = filename.slice(/\.\w+$/) - ["#{rand Time.now.to_i}#{base_filename}", ext || ''] - end - - def sanitize_filename(filename) - return unless filename - filename.strip.tap do |name| - # NOTE: File.basename doesn't work right with Windows paths on Unix - # get only the filename, not the whole path - name.gsub! /^.*(\\|\/)/, '' - - # Finally, replace all non alphanumeric, underscore or periods with underscore - name.gsub! /[^A-Za-z0-9\.\-]/, '_' - end - end - - # before_validation callback. - def set_size_from_temp_path - self.size = File.size(temp_path) if save_attachment? - end - - # validates the size and content_type attributes according to the current model's options - def attachment_attributes_valid? - [:size, :content_type].each do |attr_name| - enum = attachment_options[attr_name] - if Object.const_defined?(:I18n) # Rails >= 2.2 - errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name)) - else - errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name)) - end - end - end - - # Initializes a new thumbnail with the given suffix. - def find_or_initialize_thumbnail(file_name_suffix) - respond_to?(:parent_id) ? - thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, id) : - thumbnail_class.find_or_initialize_by_thumbnail(file_name_suffix.to_s) - end - - # Stub for a #process_attachment method in a processor - def process_attachment - @saved_attachment = save_attachment? - end - - # Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared. - def after_process_attachment - if @saved_attachment - if respond_to?(:process_attachment_with_processing, true) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil? - temp_file = temp_path || create_temp_file - attachment_options[:thumbnails].each { |suffix, size| - if size.is_a?(Symbol) - parent_type = polymorphic_parent_type - next unless parent_type && [parent_type, parent_type.tableize].include?(suffix.to_s) && respond_to?(size) - size = send(size) - end - if size.is_a?(Hash) - parent_type = polymorphic_parent_type - next unless parent_type && [parent_type, parent_type.tableize].include?(suffix.to_s) - size.each { |ppt_suffix, ppt_size| - create_or_update_thumbnail(temp_file, ppt_suffix, *ppt_size) - } - else - create_or_update_thumbnail(temp_file, suffix, *size) - end - } - end - save_to_storage - @temp_paths.clear - @saved_attachment = nil - #callback :after_attachment_saved - callback_with_args :after_attachment_saved, nil - end - end - - # Resizes the given processed img object with either the attachment resize options or the thumbnail resize options. - def resize_image_or_thumbnail!(img) - if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image - resize_image(img, attachment_options[:resize_to]) - elsif thumbnail_resize_options # thumbnail - resize_image(img, thumbnail_resize_options) - end - end - - if defined?(Rails) && Rails::VERSION::MAJOR >= 3 - def callback_with_args(method, arg = self) - if respond_to?(method) - send(method, arg) - end - end - # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self. - # Only accept blocks, however - elsif ActiveSupport.const_defined?(:Callbacks) - # Rails 2.1 and beyond! - def callback_with_args(method, arg = self) - notify(method) - - result = run_callbacks(method, { :object => arg }) { |result, object| result == false } - - if result != false && respond_to_without_attributes?(method) - result = send(method) - end - - result - end - - def run_callbacks(kind, options = {}, &block) - options.reverse_merge!( :object => self ) - self.class.send("#{kind}_callback_chain").run(options[:object], options, &block) - end - else - # Rails 2.0 - def callback_with_args(method, arg = self) - notify(method) - - result = nil - callbacks_for(method).each do |callback| - result = callback.call(self, arg) - return false if result == false - end - result - end - end - - # Removes the thumbnails for the attachment, if it has any - def destroy_thumbnails - self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable? - end - - def polymorphic_parent_type - rel_name = self.class.polymorphic_relation_type_column - rel_name && send(rel_name) - end - - def get_jpeg_quality(require_0_to_100 = true) - quality = attachment_options[:jpeg_quality] - if quality.is_a?(Hash) - sbl_quality = thumbnail && quality[thumbnail.to_sym] - sbl_quality = nil if sbl_quality && require_0_to_100 && !sbl_quality.to_i.between?(0, 100) - surface = (width || 1) * (height || 1) - size_quality = quality.detect { |k, v| - next unless k.is_a?(String) && k =~ /^(<|>=)(\d+)$/ - op, threshold = $1, $2.to_i - surface.send(op, threshold) - } - quality = sbl_quality || size_quality && size_quality[1] - end - return quality && (!require_0_to_100 || quality.to_i.between?(0, 100)) ? quality : nil - end - end - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb deleted file mode 100644 index a779195..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb +++ /dev/null @@ -1,211 +0,0 @@ -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - module Backends - # = CloudFiles Storage Backend - # - # Enables use of {Rackspace Cloud Files}[http://www.mosso.com/cloudfiles.jsp] as a storage mechanism - # - # Based heavily on the Amazon S3 backend. - # - # == Requirements - # - # Requires the {Cloud Files Gem}[http://www.mosso.com/cloudfiles.jsp] by Rackspace - # - # == Configuration - # - # Configuration is done via Rails.root.to_s/config/rackspace_cloudfiles.yml and is loaded according to the #{Rails.env}. - # The minimum connection options that you must specify are a container name, your Mosso login name and your Mosso API key. - # You can sign up for Cloud Files and get access keys by visiting https://www.mosso.com/buy.htm - # - # Example configuration (Rails.root.to_s/config/rackspace_cloudfiles.yml) - # - # development: - # container_name: appname_development - # username: - # api_key: - # - # test: - # container_name: appname_test - # username: - # api_key: - # - # production: - # container_name: appname - # username: - # apik_key: - # - # You can change the location of the config path by passing a full path to the :cloudfiles_config_path option. - # - # has_attachment :storage => :cloud_files, :cloudfiles_config_path => (Rails.root.to_s + '/config/mosso.yml') - # - # === Required configuration parameters - # - # * :username - The username for your Rackspace Cloud (Mosso) account. Provided by Rackspace. - # * :secret_access_key - The api key for your Rackspace Cloud account. Provided by Rackspace. - # * :container_name - The name of a container in your Cloud Files account. - # - # If any of these required arguments is missing, a AuthenticationException will be raised from CloudFiles::Connection. - # - # == Usage - # - # To specify Cloud Files as the storage mechanism for a model, set the acts_as_attachment :storage option to :cloud_files/tt>. - # - # class Photo < ActiveRecord::Base - # has_attachment :storage => :cloud_files - # end - # - # === Customizing the path - # - # By default, files are prefixed using a pseudo hierarchy in the form of :table_name/:id, which results - # in Cloud Files object names (and urls) that look like: http://:server/:container_name/:table_name/:id/:filename with :table_name - # representing the customizable portion of the path. You can customize this prefix using the :path_prefix - # option: - # - # class Photo < ActiveRecord::Base - # has_attachment :storage => :cloud_files, :path_prefix => 'my/custom/path' - # end - # - # Which would result in public URLs like http(s)://:server/:container_name/my/custom/path/:id/:filename. - # - # === Permissions - # - # File permisisons are determined by the permissions of the container. At present, the options are public (and distributed - # by the Limelight CDN), and private (only available to your login) - # - # === Other options - # - # Of course, all the usual configuration options apply, such as content_type and thumbnails: - # - # class Photo < ActiveRecord::Base - # has_attachment :storage => :cloud_files, :content_type => ['application/pdf', :image], :resize_to => 'x50' - # has_attachment :storage => :cloud_files, :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } - # end - # - # === Accessing Cloud Files URLs - # - # You can get an object's public URL using the cloudfiles_url accessor. For example, assuming that for your postcard app - # you had a container name like 'postcard_world_development', and an attachment model called Photo: - # - # @postcard.cloudfiles_url # => http://cdn.cloudfiles.mosso.com/c45182/uploaded_files/20/london.jpg - # - # The resulting url is in the form: http://:server/:container_name/:table_name/:id/:file. - # The optional thumbnail argument will output the thumbnail's filename (if any). - # - # Additionally, you can get an object's base path relative to the container root using - # base_path: - # - # @photo.file_base_path # => uploaded_files/20 - # - # And the full path (including the filename) using full_filename: - # - # @photo.full_filename # => uploaded_files/20/london.jpg - # - # Niether base_path or full_filename include the container name as part of the path. - # You can retrieve the container name using the container_name method. - module CloudFileBackend - class RequiredLibraryNotFoundError < StandardError; end - class ConfigFileNotFoundError < StandardError; end - - def self.included(base) #:nodoc: - mattr_reader :container_name, :cloudfiles_config - - begin - require 'cloudfiles' - rescue LoadError - raise RequiredLibraryNotFoundError.new('CloudFiles could not be loaded') - end - - begin - @@cloudfiles_config_path = base.attachment_options[:cloudfiles_config_path] || (Rails.root.to_s + '/config/rackspace_cloudfiles.yml') - @@cloudfiles_config = @@cloudfiles_config = YAML.load(ERB.new(File.read(@@cloudfiles_config_path)).result)[Rails.env].symbolize_keys - rescue - #raise ConfigFileNotFoundError.new('File %s not found' % @@cloudfiles_config_path) - end - - @@container_name = @@cloudfiles_config[:container_name] - @@cf = CloudFiles::Connection.new(@@cloudfiles_config[:username], @@cloudfiles_config[:api_key]) - @@container = @@cf.container(@@container_name) - - base.before_update :rename_file - end - - # Overwrites the base filename writer in order to store the old filename - def filename=(value) - @old_filename = filename unless filename.nil? || @old_filename - write_attribute :filename, sanitize_filename(value) - end - - # The attachment ID used in the full path of a file - def attachment_path_id - ((respond_to?(:parent_id) && parent_id) || id).to_s - end - - # The pseudo hierarchy containing the file relative to the container name - # Example: :table_name/:id - def base_path - File.join(attachment_options[:path_prefix], attachment_path_id) - end - - # The full path to the file relative to the container name - # Example: :table_name/:id/:filename - def full_filename(thumbnail = nil) - File.join(base_path, thumbnail_name_for(thumbnail)) - end - - # All public objects are accessible via a GET request to the Cloud Files servers. You can generate a - # url for an object using the cloudfiles_url method. - # - # @photo.cloudfiles_url - # - # The resulting url is in the CDN URL for the object - # - # The optional thumbnail argument will output the thumbnail's filename (if any). - # - # If you are trying to get the URL for a nonpublic container, nil will be returned. - def cloudfiles_url(thumbnail = nil) - if @@container.public? - File.join(@@container.cdn_url, full_filename(thumbnail)) - else - nil - end - end - alias :public_filename :cloudfiles_url - - def create_temp_file - write_to_temp_file current_data - end - - def current_data - @@container.get_object(full_filename).data - end - - protected - # Called in the after_destroy callback - def destroy_file - @@container.delete_object(full_filename) - end - - def rename_file - # Cloud Files doesn't rename right now, so we'll just nuke. - return unless @old_filename && @old_filename != filename - - old_full_filename = File.join(base_path, @old_filename) - @@container.delete_object(old_full_filename) - - @old_filename = nil - true - end - - def save_to_storage - if save_attachment? - @object = @@container.create_object(full_filename) - @object.write((temp_path ? File.open(temp_path) : temp_data)) - end - - @old_filename = nil - true - end - end - end - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/db_file_backend.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/db_file_backend.rb deleted file mode 100644 index 23881e7..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/db_file_backend.rb +++ /dev/null @@ -1,39 +0,0 @@ -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - module Backends - # Methods for DB backed attachments - module DbFileBackend - def self.included(base) #:nodoc: - Object.const_set(:DbFile, Class.new(ActiveRecord::Base)) unless Object.const_defined?(:DbFile) - base.belongs_to :db_file, :class_name => '::DbFile', :foreign_key => 'db_file_id' - end - - # Creates a temp file with the current db data. - def create_temp_file - write_to_temp_file current_data - end - - # Gets the current data from the database - def current_data - db_file.data - end - - protected - # Destroys the file. Called in the after_destroy callback - def destroy_file - db_file.destroy if db_file - end - - # Saves the data to the DbFile model - def save_to_storage - if save_attachment? - (db_file || build_db_file).data = temp_data - db_file.save! - self.class.update_all ['db_file_id = ?', self.db_file_id = db_file.id], ['id = ?', id] - end - true - end - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb deleted file mode 100644 index 985fae1..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb +++ /dev/null @@ -1,126 +0,0 @@ -require 'fileutils' -require 'digest/sha2' - -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - module Backends - # Methods for file system backed attachments - module FileSystemBackend - def self.included(base) #:nodoc: - base.before_update :rename_file - end - - # Gets the full path to the filename in this format: - # - # # This assumes a model name like MyModel - # # public/#{table_name} is the default filesystem path - # #{Rails.root}/public/my_models/5/blah.jpg - # - # Overwrite this method in your model to customize the filename. - # The optional thumbnail argument will output the thumbnail's filename. - def full_filename(thumbnail = nil) - file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s - File.join(Rails.root, file_system_path, *partitioned_path(thumbnail_name_for(thumbnail))) - end - - # Used as the base path that #public_filename strips off full_filename to create the public path - def base_path - @base_path ||= File.join(Rails.root, 'public') - end - - # The attachment ID used in the full path of a file - def attachment_path_id - ((respond_to?(:parent_id) && parent_id) || id) || 0 - end - - # Partitions the given path into an array of path components. - # - # For example, given an *args of ["foo", "bar"], it will return - # ["0000", "0001", "foo", "bar"] (assuming that that id returns 1). - # - # If the id is not an integer, then path partitioning will be performed by - # hashing the string value of the id with SHA-512, and splitting the result - # into 4 components. If the id a 128-bit UUID (as set by :uuid_primary_key => true) - # then it will be split into 2 components. - # - # To turn this off entirely, set :partition => false. - def partitioned_path(*args) - if respond_to?(:attachment_options) && attachment_options[:partition] == false - args - elsif attachment_options[:uuid_primary_key] - # Primary key is a 128-bit UUID in hex format. Split it into 2 components. - path_id = attachment_path_id.to_s - component1 = path_id[0..15] || "-" - component2 = path_id[16..-1] || "-" - [component1, component2] + args - else - path_id = attachment_path_id - if path_id.is_a?(Integer) - # Primary key is an integer. Split it after padding it with 0. - ("%08d" % path_id).scan(/..../) + args - else - # Primary key is a String. Hash it, then split it into 4 components. - hash = Digest::SHA512.hexdigest(path_id.to_s) - [hash[0..31], hash[32..63], hash[64..95], hash[96..127]] + args - end - end - end - - # Gets the public path to the file - # The optional thumbnail argument will output the thumbnail's filename. - def public_filename(thumbnail = nil) - full_filename(thumbnail).gsub %r(^#{Regexp.escape(base_path)}), '' - end - - def filename=(value) - @old_filename = full_filename unless filename.nil? || @old_filename - write_attribute :filename, sanitize_filename(value) - end - - # Creates a temp file from the currently saved file. - def create_temp_file - copy_to_temp_file full_filename - end - - protected - # Destroys the file. Called in the after_destroy callback - def destroy_file - FileUtils.rm full_filename - # remove directory also if it is now empty - Dir.rmdir(File.dirname(full_filename)) if (Dir.entries(File.dirname(full_filename))-['.','..']).empty? - rescue - logger.info "Exception destroying #{full_filename.inspect}: [#{$!.class.name}] #{$1.to_s}" - logger.warn $!.backtrace.collect { |b| " > #{b}" }.join("\n") - end - - # Renames the given file before saving - def rename_file - return unless @old_filename && @old_filename != full_filename - if save_attachment? && File.exists?(@old_filename) - FileUtils.rm @old_filename - elsif File.exists?(@old_filename) - FileUtils.mv @old_filename, full_filename - end - @old_filename = nil - true - end - - # Saves the file to the file system - def save_to_storage - if save_attachment? - # TODO: This overwrites the file if it exists, maybe have an allow_overwrite option? - FileUtils.mkdir_p(File.dirname(full_filename)) - FileUtils.cp(temp_path, full_filename) - FileUtils.chmod(attachment_options[:chmod] || 0644, full_filename) - end - @old_filename = nil - true - end - - def current_data - File.file?(full_filename) ? File.read(full_filename) : nil - end - end - end - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb deleted file mode 100644 index 6532dd0..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb +++ /dev/null @@ -1,412 +0,0 @@ -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - module Backends - # = AWS::S3 Storage Backend - # - # Enables use of {Amazon's Simple Storage Service}[http://aws.amazon.com/s3] as a storage mechanism - # - # == Requirements - # - # Requires the {AWS::S3 Library}[http://amazon.rubyforge.org] for S3 by Marcel Molina Jr. installed either - # as a gem or a as a Rails plugin. - # - # == Configuration - # - # Configuration is done via #{Rails.root}/config/amazon_s3.yml and is loaded according to the #{Rails.env}. - # The minimum connection options that you must specify are a bucket name, your access key id and your secret access key. - # If you don't already have your access keys, all you need to sign up for the S3 service is an account at Amazon. - # You can sign up for S3 and get access keys by visiting http://aws.amazon.com/s3. - # - # If you wish to use Amazon CloudFront to serve the files, you can also specify a distibution domain for the bucket. - # To read more about CloudFront, visit http://aws.amazon.com/cloudfront - # - # Example configuration (#{Rails.root}/config/amazon_s3.yml) - # - # development: - # bucket_name: appname_development - # access_key_id: - # secret_access_key: - # distribution_domain: XXXX.cloudfront.net - # - # test: - # bucket_name: appname_test - # access_key_id: - # secret_access_key: - # distribution_domain: XXXX.cloudfront.net - # - # production: - # bucket_name: appname - # access_key_id: - # secret_access_key: - # distribution_domain: XXXX.cloudfront.net - # - # You can change the location of the config path by passing a full path to the :s3_config_path option. - # - # has_attachment :storage => :s3, :s3_config_path => (#{Rails.root} + '/config/s3.yml') - # - # === Required configuration parameters - # - # * :access_key_id - The access key id for your S3 account. Provided by Amazon. - # * :secret_access_key - The secret access key for your S3 account. Provided by Amazon. - # * :bucket_name - A unique bucket name (think of the bucket_name as being like a database name). - # - # If any of these required arguments is missing, a MissingAccessKey exception will be raised from AWS::S3. - # - # == About bucket names - # - # Bucket names have to be globaly unique across the S3 system. And you can only have up to 100 of them, - # so it's a good idea to think of a bucket as being like a database, hence the correspondance in this - # implementation to the development, test, and production environments. - # - # The number of objects you can store in a bucket is, for all intents and purposes, unlimited. - # - # === Optional configuration parameters - # - # * :server - The server to make requests to. Defaults to s3.amazonaws.com. - # * :port - The port to the requests should be made on. Defaults to 80 or 443 if :use_ssl is set. - # * :use_ssl - If set to true, :port will be implicitly set to 443, unless specified otherwise. Defaults to false. - # * :distribution_domain - The CloudFront distribution domain for the bucket. This can either be the assigned - # distribution domain (ie. XXX.cloudfront.net) or a chosen domain using a CNAME. See CloudFront for more details. - # - # == Usage - # - # To specify S3 as the storage mechanism for a model, set the acts_as_attachment :storage option to :s3. - # - # class Photo < ActiveRecord::Base - # has_attachment :storage => :s3 - # end - # - # === Customizing the path - # - # By default, files are prefixed using a pseudo hierarchy in the form of :table_name/:id, which results - # in S3 urls that look like: http(s)://:server/:bucket_name/:table_name/:id/:filename with :table_name - # representing the customizable portion of the path. You can customize this prefix using the :path_prefix - # option: - # - # class Photo < ActiveRecord::Base - # has_attachment :storage => :s3, :path_prefix => 'my/custom/path' - # end - # - # Which would result in URLs like http(s)://:server/:bucket_name/my/custom/path/:id/:filename. - # - # === Using different bucket names on different models - # - # By default the bucket name that the file will be stored to is the one specified by the - # :bucket_name key in the amazon_s3.yml file. You can use the :bucket_key option - # to overide this behavior on a per model basis. For instance if you want a bucket that will hold - # only Photos you can do this: - # - # class Photo < ActiveRecord::Base - # has_attachment :storage => :s3, :bucket_key => :photo_bucket_name - # end - # - # And then your amazon_s3.yml file needs to look like this. - # - # development: - # bucket_name: appname_development - # access_key_id: - # secret_access_key: - # - # test: - # bucket_name: appname_test - # access_key_id: - # secret_access_key: - # - # production: - # bucket_name: appname - # photo_bucket_name: appname_photos - # access_key_id: - # secret_access_key: - # - # If the bucket_key you specify is not there in a certain environment then attachment_fu will - # default to the bucket_name key. This way you only have to create special buckets - # this can be helpful if you only need special buckets in certain environments. - # - # === Permissions - # - # By default, files are stored on S3 with public access permissions. You can customize this using - # the :s3_access option to has_attachment. Available values are - # :private, :public_read_write, and :authenticated_read. - # - # === Other options - # - # Of course, all the usual configuration options apply, such as content_type and thumbnails: - # - # class Photo < ActiveRecord::Base - # has_attachment :storage => :s3, :content_type => ['application/pdf', :image], :resize_to => 'x50' - # has_attachment :storage => :s3, :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } - # end - # - # === Accessing S3 URLs - # - # You can get an object's URL using the s3_url accessor. For example, assuming that for your postcard app - # you had a bucket name like 'postcard_world_development', and an attachment model called Photo: - # - # @postcard.s3_url # => http(s)://s3.amazonaws.com/postcard_world_development/photos/1/mexico.jpg - # - # The resulting url is in the form: http(s)://:server/:bucket_name/:table_name/:id/:file. - # The optional thumbnail argument will output the thumbnail's filename (if any). - # - # Additionally, you can get an object's base path relative to the bucket root using - # base_path: - # - # @photo.file_base_path # => photos/1 - # - # And the full path (including the filename) using full_filename: - # - # @photo.full_filename # => photos/ - # - # Niether base_path or full_filename include the bucket name as part of the path. - # You can retrieve the bucket name using the bucket_name method. - # - # === Accessing CloudFront URLs - # - # You can get an object's CloudFront URL using the cloudfront_url accessor. Using the example from above: - # @postcard.cloudfront_url # => http://XXXX.cloudfront.net/photos/1/mexico.jpg - # - # The resulting url is in the form: http://:distribution_domain/:table_name/:id/:file - # - # If you set :cloudfront to true in your model, the public_filename will be the CloudFront - # URL, not the S3 URL. - module S3Backend - class RequiredLibraryNotFoundError < StandardError; end - class ConfigFileNotFoundError < StandardError; end - - def self.included(base) #:nodoc: - mattr_reader :bucket_name, :s3_config - - begin - require 'aws/s3' - include AWS::S3 - rescue LoadError - raise RequiredLibraryNotFoundError.new('AWS::S3 could not be loaded') - end - - begin - @@s3_config_path = base.attachment_options[:s3_config_path] || File.join(Rails.root, 'config', 'amazon_s3.yml') - @@s3_config = @@s3_config = YAML.load(ERB.new(File.read(@@s3_config_path)).result)[Rails.env].symbolize_keys - #rescue - # raise ConfigFileNotFoundError.new('File %s not found' % @@s3_config_path) - end - - bucket_key = base.attachment_options[:bucket_key] - - if bucket_key and s3_config[bucket_key.to_sym] - eval_string = "def bucket_name()\n \"#{s3_config[bucket_key.to_sym]}\"\nend" - else - eval_string = "def bucket_name()\n \"#{s3_config[:bucket_name]}\"\nend" - end - base.class_eval(eval_string, __FILE__, __LINE__) - - Base.establish_connection!(s3_config.slice(:access_key_id, :secret_access_key, :server, :port, :use_ssl, :persistent, :proxy)) - - # Bucket.create(@@bucket_name) - - base.before_update :rename_file - end - - def self.protocol - @protocol ||= s3_config[:use_ssl] ? 'https://' : 'http://' - end - - def self.hostname - @hostname ||= s3_config[:server] || AWS::S3::DEFAULT_HOST - end - - def self.port_string - @port_string ||= (s3_config[:port].nil? || s3_config[:port] == (s3_config[:use_ssl] ? 443 : 80)) ? '' : ":#{s3_config[:port]}" - end - - def self.distribution_domain - @distribution_domain = s3_config[:distribution_domain] - end - - module ClassMethods - def s3_protocol - Technoweenie::AttachmentFu::Backends::S3Backend.protocol - end - - def s3_hostname - Technoweenie::AttachmentFu::Backends::S3Backend.hostname - end - - def s3_port_string - Technoweenie::AttachmentFu::Backends::S3Backend.port_string - end - - def cloudfront_distribution_domain - Technoweenie::AttachmentFu::Backends::S3Backend.distribution_domain - end - end - - # Overwrites the base filename writer in order to store the old filename - def filename=(value) - @old_filename = filename unless filename.nil? || @old_filename - write_attribute :filename, sanitize_filename(value) - end - - # The attachment ID used in the full path of a file - def attachment_path_id - ((respond_to?(:parent_id) && parent_id) || id).to_s - end - - # The pseudo hierarchy containing the file relative to the bucket name - # Example: :table_name/:id - def base_path - File.join(attachment_options[:path_prefix], attachment_path_id) - end - - # The full path to the file relative to the bucket name - # Example: :table_name/:id/:filename - def full_filename(thumbnail = nil) - File.join(base_path, thumbnail_name_for(thumbnail)) - end - - # All public objects are accessible via a GET request to the S3 servers. You can generate a - # url for an object using the s3_url method. - # - # @photo.s3_url - # - # The resulting url is in the form: http(s)://:server/:bucket_name/:table_name/:id/:file where - # the :server variable defaults to AWS::S3 URL::DEFAULT_HOST (s3.amazonaws.com) and can be - # set using the configuration parameters in #{Rails.root}/config/amazon_s3.yml. - # - # The optional thumbnail argument will output the thumbnail's filename (if any). - def s3_url(thumbnail = nil) - File.join(s3_protocol + s3_hostname + s3_port_string, bucket_name, full_filename(thumbnail)) - end - - # All public objects are accessible via a GET request to CloudFront. You can generate a - # url for an object using the cloudfront_url method. - # - # @photo.cloudfront_url - # - # The resulting url is in the form: http://:distribution_domain/:table_name/:id/:file using - # the :distribution_domain variable set in the configuration parameters in #{Rails.root}/config/amazon_s3.yml. - # - # The optional thumbnail argument will output the thumbnail's filename (if any). - def cloudfront_url(thumbnail = nil) - s3_protocol + cloudfront_distribution_domain + "/" + full_filename(thumbnail) - end - - def public_filename(*args) - if attachment_options[:cloudfront] - cloudfront_url(*args) - else - s3_url(*args) - end - end - - # All private objects are accessible via an authenticated GET request to the S3 servers. You can generate an - # authenticated url for an object like this: - # - # @photo.authenticated_s3_url - # - # By default authenticated urls expire 5 minutes after they were generated. - # - # Expiration options can be specified either with an absolute time using the :expires option, - # or with a number of seconds relative to now with the :expires_in option: - # - # # Absolute expiration date (October 13th, 2025) - # @photo.authenticated_s3_url(:expires => Time.mktime(2025,10,13).to_i) - # - # # Expiration in five hours from now - # @photo.authenticated_s3_url(:expires_in => 5.hours) - # - # You can specify whether the url should go over SSL with the :use_ssl option. - # By default, the ssl settings for the current connection will be used: - # - # @photo.authenticated_s3_url(:use_ssl => true) - # - # Finally, the optional thumbnail argument will output the thumbnail's filename (if any): - # - # @photo.authenticated_s3_url('thumbnail', :expires_in => 5.hours, :use_ssl => true) - def authenticated_s3_url(*args) - options = args.extract_options! - options[:expires_in] = options[:expires_in].to_i if options[:expires_in] - thumbnail = args.shift - S3Object.url_for(full_filename(thumbnail), bucket_name, options) - end - - def create_temp_file - write_to_temp_file current_data - end - - def current_data - if attachment_options[:encrypted_storage] && self.respond_to?(:encryption_key) && self.encryption_key != nil - EncryptedData.decrypt_data(S3Object.value(full_filename, bucket_name), self.encryption_key) - else - S3Object.value full_filename, bucket_name - end - end - - def s3_protocol - Technoweenie::AttachmentFu::Backends::S3Backend.protocol - end - - def s3_hostname - Technoweenie::AttachmentFu::Backends::S3Backend.hostname - end - - def s3_port_string - Technoweenie::AttachmentFu::Backends::S3Backend.port_string - end - - def cloudfront_distribution_domain - Technoweenie::AttachmentFu::Backends::S3Backend.distribution_domain - end - - protected - # Called in the after_destroy callback - def destroy_file - S3Object.delete full_filename, bucket_name - end - - def rename_file - return unless @old_filename && @old_filename != filename - - old_full_filename = File.join(base_path, @old_filename) - - S3Object.rename( - old_full_filename, - full_filename, - bucket_name, - :access => attachment_options[:s3_access] - ) - - @old_filename = nil - true - end - - def save_to_storage - if save_attachment? - if attachment_options[:encrypted_storage] - S3Object.store( - full_filename, - (temp_path ? File.open(temp_path) : temp_data), - bucket_name, - :content_type => content_type, - :cache_control => attachment_options[:cache_control], - :access => attachment_options[:s3_access], - 'x-amz-server-side-encryption' => 'AES256', - 'Content-Disposition' => "attachment; filename=\"#{filename}\"" - ) - else - S3Object.store( - full_filename, - (temp_path ? File.open(temp_path) : temp_data), - bucket_name, - :content_type => content_type, - :cache_control => attachment_options[:cache_control], - :access => attachment_options[:s3_access] - ) - end - end - - @old_filename = nil - true - end - end - end - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb deleted file mode 100644 index d78e8d0..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb +++ /dev/null @@ -1,66 +0,0 @@ -require 'red_artisan/core_image/processor' - -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - module Processors - module CoreImageProcessor - def self.included(base) - base.send :extend, ClassMethods - base.alias_method_chain :process_attachment, :processing - end - - module ClassMethods - def with_image(file, &block) - block.call OSX::CIImage.from(file) - end - end - - protected - def process_attachment_with_processing - return unless process_attachment_without_processing - with_image do |img| - self.width = img.extent.size.width if respond_to?(:width) - self.height = img.extent.size.height if respond_to?(:height) - resize_image_or_thumbnail! img - callback_with_args :after_resize, img - end if image? - end - - # Performs the actual resizing operation for a thumbnail - def resize_image(img, size) - processor = ::RedArtisan::CoreImage::Processor.new(img) - size = size.first if size.is_a?(Array) && size.length == 1 - if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) - if size.is_a?(Fixnum) - processor.fit(size) - else - processor.resize(size[0], size[1]) - end - else - new_size = [img.extent.size.width, img.extent.size.height] / size.to_s - processor.resize(new_size[0], new_size[1]) - end - - processor.render do |result| - self.width = result.extent.size.width if respond_to?(:width) - self.height = result.extent.size.height if respond_to?(:height) - out_file = random_tempfile_filename - temp_paths.unshift Tempfile.new(out_file, Technoweenie::AttachmentFu.tempfile_path).path - properties = nil - # We don't check the source image since we're forcing the output to JPEG, apparently… - # Beware: apparently CoreImage only takes the percentage as a HINT, using a different actual quality… - quality = get_jpeg_quality - properties = { OSX::NSImageCompressionFactor => quality / 100.0 } if quality - result.save(self.temp_path, OSX::NSJPEGFileType, properties) - # - # puts "#{self.temp_path} @ #{quality.inspect} -> #{%x(identify -format '%Q' "#{self.temp_path}")}" - # - self.size = File.size(self.temp_path) - end - end - end - end - end -end - - diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb deleted file mode 100644 index ea00713..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'rubygems' -require 'gd2' -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - module Processors - module Gd2Processor - def self.included(base) - base.send :extend, ClassMethods - base.alias_method_chain :process_attachment, :processing - end - - module ClassMethods - # Yields a block containing a GD2 Image for the given binary data. - def with_image(file, &block) - im = GD2::Image.import(file) - block.call(im) - end - end - - protected - def process_attachment_with_processing - return unless process_attachment_without_processing && image? - with_image do |img| - resize_image_or_thumbnail! img - self.width = img.width - self.height = img.height - callback_with_args :after_resize, img - end - end - - # Performs the actual resizing operation for a thumbnail - def resize_image(img, size) - size = size.first if size.is_a?(Array) && size.length == 1 - if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) - if size.is_a?(Fixnum) - # Borrowed from image science's #thumbnail method and adapted - # for this. - scale = size.to_f / (img.width > img.height ? img.width.to_f : img.height.to_f) - img.resize!((img.width * scale).round(1), (img.height * scale).round(1), false) - else - img.resize!(size.first, size.last, false) - end - else - w, h = [img.width, img.height] / size.to_s - img.resize!(w, h, false) - end - self.width = img.width if respond_to?(:width) - self.height = img.height if respond_to?(:height) - out_file = random_tempfile_filename - temp_paths.unshift out_file - jpeg = out_file =~ /\.jpe?g\z/i - quality = jpeg && get_jpeg_quality - self.size = img.export(self.temp_path, quality ? { :quality => quality } : {}) - end - - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb deleted file mode 100644 index 44da9dd..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb +++ /dev/null @@ -1,80 +0,0 @@ -require 'image_science' -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - module Processors - module ImageScienceProcessor - def self.included(base) - base.send :extend, ClassMethods - base.alias_method_chain :process_attachment, :processing - end - - module ClassMethods - # Yields a block containing an Image Science image for the given binary data. - def with_image(file, &block) - ::ImageScience.with_image file, &block - end - end - - protected - def process_attachment_with_processing - return unless process_attachment_without_processing && image? - with_image do |img| - self.width = img.width if respond_to?(:width) - self.height = img.height if respond_to?(:height) - resize_image_or_thumbnail! img - end - end - - # Performs the actual resizing operation for a thumbnail - def resize_image(img, size) - # create a dummy temp file to write to - # ImageScience doesn't handle all gifs properly, so it converts them to - # pngs for thumbnails. It has something to do with trying to save gifs - # with a larger palette than 256 colors, which is all the gif format - # supports. - filename.sub! /gif$/i, 'png' - content_type.sub!(/gif$/, 'png') - temp_paths.unshift write_to_temp_file(filename) - grab_dimensions = lambda do |img| - self.width = img.width if respond_to?(:width) - self.height = img.height if respond_to?(:height) - - # We don't check for quality being a 0-100 value as we also allow FreeImage JPEG_xxx constants. - quality = content_type[/jpe?g/i] && get_jpeg_quality(false) - # Traditional ImageScience has a 1-arg save method, tdd-image_science has 1 mandatory + 1 optional - if quality && img.method(:save).arity == -2 - img.save self.temp_path, quality - else - img.save self.temp_path - end - self.size = File.size(self.temp_path) - callback_with_args :after_resize, img - end - - size = size.first if size.is_a?(Array) && size.length == 1 - if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) - if size.is_a?(Fixnum) - img.thumbnail(size, &grab_dimensions) - else - img.resize(size[0], size[1], &grab_dimensions) - end - else - new_size = [img.width, img.height] / size.to_s - if size.ends_with?('!') - aspect = new_size[0].to_f / new_size[1].to_f - ih, iw = img.height, img.width - w, h = (ih * aspect), (iw / aspect) - w = [iw, w].min.to_i - h = [ih, h].min.to_i - img.with_crop((iw-w)/2, (ih-h)/2, (iw+w)/2, (ih+h)/2) { |crop| - crop.resize(new_size[0], new_size[1], &grab_dimensions) - } - else - img.resize(new_size[0], new_size[1], &grab_dimensions) - end - end - end - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb deleted file mode 100644 index 2a37b3a..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb +++ /dev/null @@ -1,142 +0,0 @@ -require 'mini_magick' -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - module Processors - module MiniMagickProcessor - def self.included(base) - base.send :extend, ClassMethods - base.alias_method_chain :process_attachment, :processing - end - - module ClassMethods - # Yields a block containing an MiniMagick Image for the given binary data. - def with_image(file, &block) - begin - binary_data = file.is_a?(MiniMagick::Image) ? file : MiniMagick::Image.open(file) unless !Object.const_defined?(:MiniMagick) - rescue - # Log the failure to load the image. - logger.debug("Exception working with image: #{$!}") - binary_data = nil - end - block.call binary_data if block && binary_data - ensure - !binary_data.nil? - end - end - - protected - def process_attachment_with_processing - return unless process_attachment_without_processing - with_image do |img| - resize_image_or_thumbnail! img - self.width = img[:width] if respond_to?(:width) - self.height = img[:height] if respond_to?(:height) - callback_with_args :after_resize, img - end if image? - end - - # Performs the actual resizing operation for a thumbnail - def resize_image(img, size) - size = size.first if size.is_a?(Array) && size.length == 1 - format = img[:format] - img.combine_options do |commands| - commands.strip unless attachment_options[:keep_profile] - - # GIF is not handled correctly, so we move to PNG, as in other processors… - if format == 'GIF' - img.format('PNG') - end - - if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) - if size.is_a?(Fixnum) - size = [size, size] - commands.resize(size.join('x')) - else - commands.resize(size.join('x') + '!') - end - # extend to thumbnail size - elsif size.is_a?(String) and size =~ /e$/ - size = size.gsub(/e/, '') - commands.resize(size.to_s + '>') - commands.background('#ffffff') - commands.gravity('center') - commands.extent(size) - # crop thumbnail, the smart way - elsif size.is_a?(String) and size =~ /c$/ - size = size.gsub(/c/, '') - - # calculate sizes and aspect ratio - thumb_width, thumb_height = size.split("x") - thumb_width = thumb_width.to_f - thumb_height = thumb_height.to_f - - thumb_aspect = thumb_width.to_f / thumb_height.to_f - image_width, image_height = img[:width].to_f, img[:height].to_f - image_aspect = image_width / image_height - - # only crop if image is not smaller in both dimensions - unless image_width < thumb_width and image_height < thumb_height - command = calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect) - - # crop image - commands.extract(command) - end - - # don not resize if image is not as height or width then thumbnail - if image_width < thumb_width or image_height < thumb_height - commands.background('#ffffff') - commands.gravity('center') - commands.extent(size) - # resize image - else - commands.resize("#{size.to_s}") - end - # crop end - else - commands.resize(size.to_s) - end - end - dims = img[:dimensions] - self.width = dims[0] if respond_to?(:width) - self.height = dims[1] if respond_to?(:height) - # Has to be done this far so we get proper dimensions - if format == 'JPEG' - quality = get_jpeg_quality - img.quality(quality) if quality - end - temp_paths.unshift img - self.size = File.size(self.temp_path) - end - - def calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect) - # only crop if image is not smaller in both dimensions - - # special cases, image smaller in one dimension then thumbsize - if image_width < thumb_width - offset = (image_height / 2) - (thumb_height / 2) - command = "#{image_width}x#{thumb_height}+0+#{offset}" - elsif image_height < thumb_height - offset = (image_width / 2) - (thumb_width / 2) - command = "#{thumb_width}x#{image_height}+#{offset}+0" - - # normal thumbnail generation - # calculate height and offset y, width is fixed - elsif (image_aspect <= thumb_aspect or image_width < thumb_width) and image_height > thumb_height - height = image_width / thumb_aspect - offset = (image_height / 2) - (height / 2) - command = "#{image_width}x#{height}+0+#{offset}" - # calculate width and offset x, height is fixed - else - width = image_height * thumb_aspect - offset = (image_width / 2) - (width / 2) - command = "#{width}x#{image_height}+#{offset}+0" - end - # crop image - command - end - - - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb b/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb deleted file mode 100644 index 6dce6e3..0000000 --- a/vendor/plugins/pothoven-attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb +++ /dev/null @@ -1,66 +0,0 @@ -require 'RMagick' -module Technoweenie # :nodoc: - module AttachmentFu # :nodoc: - module Processors - module RmagickProcessor - def self.included(base) - base.send :extend, ClassMethods - base.alias_method_chain :process_attachment, :processing - end - - module ClassMethods - # Yields a block containing an RMagick Image for the given binary data. - def with_image(file, &block) - begin - binary_data = file.is_a?(Magick::Image) ? file : Magick::Image.read(file).first unless !Object.const_defined?(:Magick) - binary_data && binary_data.auto_orient! - rescue - # Log the failure to load the image. This should match ::Magick::ImageMagickError - # but that would cause acts_as_attachment to require rmagick. - logger.debug("Exception working with image: #{$!}") - binary_data = nil - end - block.call binary_data if block && binary_data - ensure - !binary_data.nil? - end - end - - protected - def process_attachment_with_processing - return unless process_attachment_without_processing - with_image do |img| - resize_image_or_thumbnail! img - self.width = img.columns if respond_to?(:width) - self.height = img.rows if respond_to?(:height) - callback_with_args :after_resize, img - end if image? - end - - # Performs the actual resizing operation for a thumbnail - def resize_image(img, size) - size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum) - if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) - size = [size, size] if size.is_a?(Fixnum) - img.thumbnail!(*size) - elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75 - dimensions = size[1..size.size].split("x") - img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i) - else - img.change_geometry(size.to_s) { |cols, rows, image| - image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) - } - end - self.width = img.columns if respond_to?(:width) - self.height = img.rows if respond_to?(:height) - img = img.sharpen if attachment_options[:sharpen_on_resize] && img.changed? - img.strip! unless attachment_options[:keep_profile] - quality = img.format.to_s[/JPEG/] && get_jpeg_quality - out_file = write_to_temp_file(img.to_blob { self.quality = quality if quality }) - temp_paths.unshift out_file - self.size = File.size(self.temp_path) - end - end - end - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/rackspace_cloudfiles.yml.tpl b/vendor/plugins/pothoven-attachment_fu/rackspace_cloudfiles.yml.tpl deleted file mode 100644 index ede689b..0000000 --- a/vendor/plugins/pothoven-attachment_fu/rackspace_cloudfiles.yml.tpl +++ /dev/null @@ -1,14 +0,0 @@ -development: - container_name: appname_development - username: - api_key: - -test: - container_name: appname_test - username: - api_key: - -production: - container_name: appname_production - username: - api_key: diff --git a/vendor/plugins/pothoven-attachment_fu/test/backends/db_file_test.rb b/vendor/plugins/pothoven-attachment_fu/test/backends/db_file_test.rb deleted file mode 100644 index e95bb49..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/backends/db_file_test.rb +++ /dev/null @@ -1,16 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) - -class DbFileTest < Test::Unit::TestCase - include BaseAttachmentTests - attachment_model Attachment - - def test_should_call_after_attachment_saved(klass = Attachment) - attachment_model.saves = 0 - assert_created do - upload_file :filename => '/files/rails.png' - end - assert_equal 1, attachment_model.saves - end - - test_against_subclass :test_should_call_after_attachment_saved, Attachment -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/backends/file_system_test.rb b/vendor/plugins/pothoven-attachment_fu/test/backends/file_system_test.rb deleted file mode 100644 index 8896477..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/backends/file_system_test.rb +++ /dev/null @@ -1,143 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) -require 'digest/sha2' - -class FileSystemTest < Test::Unit::TestCase - include BaseAttachmentTests - attachment_model FileAttachment - - def test_filesystem_size_for_file_attachment(klass = FileAttachment) - attachment_model klass - assert_created 1 do - attachment = upload_file :filename => '/files/rails.png' - assert_equal attachment.size, File.open(attachment.full_filename).stat.size - end - end - - test_against_subclass :test_filesystem_size_for_file_attachment, FileAttachment - - def test_should_not_overwrite_file_attachment(klass = FileAttachment) - attachment_model klass - assert_created 2 do - real = upload_file :filename => '/files/rails.png' - assert_valid real - assert !real.new_record?, real.errors.full_messages.join("\n") - assert !real.size.zero? - - fake = upload_file :filename => '/files/fake/rails.png' - assert_valid fake - assert !fake.size.zero? - - assert_not_equal File.open(real.full_filename).stat.size, File.open(fake.full_filename).stat.size - end - end - - test_against_subclass :test_should_not_overwrite_file_attachment, FileAttachment - - def test_should_store_file_attachment_in_filesystem(klass = FileAttachment) - attachment_model klass - attachment = nil - assert_created do - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" - end - attachment - end - - test_against_subclass :test_should_store_file_attachment_in_filesystem, FileAttachment - - def test_should_delete_old_file_when_updating(klass = FileAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - old_filename = attachment.full_filename - assert_not_created do - use_temp_file 'files/rails.png' do |file| - attachment.filename = 'rails2.png' - attachment.temp_paths.unshift File.join(FIXTURE_PATH, file) - attachment.save! - assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" - assert !File.exists?(old_filename), "#{old_filename} still exists" - end - end - end - - test_against_subclass :test_should_delete_old_file_when_updating, FileAttachment - - def test_should_delete_old_file_when_renaming(klass = FileAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - old_filename = attachment.full_filename - assert_not_created do - attachment.filename = 'rails2.png' - attachment.save - assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" - assert !File.exists?(old_filename), "#{old_filename} still exists" - assert !attachment.reload.size.zero? - assert_equal 'rails2.png', attachment.filename - end - end - - test_against_subclass :test_should_delete_old_file_when_renaming, FileAttachment - - def test_path_partitioning_works_on_integer_id(klass = FileAttachment) - attachment_model klass - - # Create a random attachment object, doesn't matter what. - attachment = upload_file :filename => '/files/rails.png' - old_id = attachment.id - attachment.id = 1 - - begin - assert_equal ["0000", "0001", "bar.txt"], attachment.send(:partitioned_path, "bar.txt") - ensure - attachment.id = old_id - end - end - - test_against_subclass :test_path_partitioning_works_on_integer_id, FileAttachment - - def test_path_partitioning_with_string_id_works_by_generating_hash(klass = FileAttachmentWithStringId) - attachment_model klass - - # Create a random attachment object, doesn't matter what. - attachment = upload_file :filename => '/files/rails.png' - old_id = attachment.id - attachment.id = "hello world some long string" - hash = Digest::SHA512.hexdigest("hello world some long string") - - begin - assert_equal [ - hash[0..31], - hash[32..63], - hash[64..95], - hash[96..127], - "bar.txt" - ], attachment.send(:partitioned_path, "bar.txt") - ensure - attachment.id = old_id - end - end - - test_against_subclass :test_path_partitioning_with_string_id_works_by_generating_hash, FileAttachmentWithStringId - - def test_path_partition_string_id_hashing_is_turned_off_if_id_is_uuid(klass = FileAttachmentWithUuid) - attachment_model klass - - # Create a random attachment object, doesn't matter what. - attachment = upload_file :filename => '/files/rails.png' - old_id = attachment.id - attachment.id = "0c0743b698483569dc65909a8cdb3bf9" - - begin - assert_equal [ - "0c0743b698483569", - "dc65909a8cdb3bf9", - "bar.txt" - ], attachment.send(:partitioned_path, "bar.txt") - ensure - attachment.id = old_id - end - end - - test_against_subclass :test_path_partition_string_id_hashing_is_turned_off_if_id_is_uuid, FileAttachmentWithUuid -end diff --git a/vendor/plugins/pothoven-attachment_fu/test/backends/remote/cloudfiles_test.rb b/vendor/plugins/pothoven-attachment_fu/test/backends/remote/cloudfiles_test.rb deleted file mode 100644 index f36dc09..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/backends/remote/cloudfiles_test.rb +++ /dev/null @@ -1,102 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper')) -require 'net/http' - -class CloudfilesTest < Test::Unit::TestCase - def self.test_CloudFiles? - true unless ENV["TEST_CLOUDFILES"] == "false" - end - - if test_CloudFiles? && File.exist?(File.join(File.dirname(__FILE__), '../../rackspace_cloudfiles.yml')) - include BaseAttachmentTests - attachment_model CloudFilesAttachment - - def test_should_create_correct_container_name(klass = CloudFilesAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_equal attachment.cloudfiles_config[:container_name], attachment.container_name - end - - test_against_subclass :test_should_create_correct_container_name, CloudFilesAttachment - - def test_should_create_default_path_prefix(klass = CloudFilesAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_equal File.join(attachment_model.table_name, attachment.attachment_path_id), attachment.base_path - end - - test_against_subclass :test_should_create_default_path_prefix, CloudFilesAttachment - - def test_should_create_custom_path_prefix(klass = CloudFilesWithPathPrefixAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_equal File.join('some/custom/path/prefix', attachment.attachment_path_id), attachment.base_path - end - - test_against_subclass :test_should_create_custom_path_prefix, CloudFilesWithPathPrefixAttachment - - - def test_should_create_valid_url(klass = CloudFilesAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_match(%r!http://cdn.cloudfiles.mosso.com/(.*?)/cloud_files_attachments/1/rails.png!, attachment.cloudfiles_url) - end - - test_against_subclass :test_should_create_valid_url, CloudFilesAttachment - - def test_should_save_attachment(klass = CloudFilesAttachment) - attachment_model klass - assert_created do - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert attachment.image? - assert !attachment.size.zero? - assert_kind_of Net::HTTPOK, http_response_for(attachment.cloudfiles_url) - end - end - - test_against_subclass :test_should_save_attachment, CloudFilesAttachment - - def test_should_delete_attachment_from_cloud_files_when_attachment_record_destroyed(klass = CloudFilesAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - - urls = [attachment.cloudfiles_url] + attachment.thumbnails.collect(&:cloudfiles_url) - - urls.each {|url| assert_kind_of Net::HTTPOK, http_response_for(url) } - attachment.destroy - urls.each do |url| - begin - http_response_for(url) - rescue Net::HTTPForbidden, Net::HTTPNotFound - nil - end - end - end - - test_against_subclass :test_should_delete_attachment_from_cloud_files_when_attachment_record_destroyed, CloudFilesAttachment - - - - protected - def http_response_for(url) - url = URI.parse(url) - Net::HTTP.start(url.host, url.port) {|http| http.request_head(url.path) } - end - - def s3_protocol - Technoweenie::AttachmentFu::Backends::S3Backend.protocol - end - - def s3_hostname - Technoweenie::AttachmentFu::Backends::S3Backend.hostname - end - - def s3_port_string - Technoweenie::AttachmentFu::Backends::S3Backend.port_string - end - else - def test_flunk_s3 - puts "s3 config file not loaded, tests not running" - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/backends/remote/s3_test.rb b/vendor/plugins/pothoven-attachment_fu/test/backends/remote/s3_test.rb deleted file mode 100644 index c7cb4f9..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/backends/remote/s3_test.rb +++ /dev/null @@ -1,119 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper')) -require 'net/http' - -class S3Test < Test::Unit::TestCase - def self.test_S3? - true unless ENV["TEST_S3"] == "false" - end - - if test_S3? && File.exist?(File.join(File.dirname(__FILE__), '../../amazon_s3.yml')) - include BaseAttachmentTests - attachment_model S3Attachment - - def test_should_create_correct_bucket_name(klass = S3Attachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_equal attachment.s3_config[:bucket_name], attachment.bucket_name - end - - test_against_subclass :test_should_create_correct_bucket_name, S3Attachment - - def test_should_create_default_path_prefix(klass = S3Attachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_equal File.join(attachment_model.table_name, attachment.attachment_path_id), attachment.base_path - end - - test_against_subclass :test_should_create_default_path_prefix, S3Attachment - - def test_should_create_custom_path_prefix(klass = S3WithPathPrefixAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_equal File.join('some/custom/path/prefix', attachment.attachment_path_id), attachment.base_path - end - - test_against_subclass :test_should_create_custom_path_prefix, S3WithPathPrefixAttachment - - def test_should_create_valid_url(klass = S3Attachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_equal "#{s3_protocol}#{s3_hostname}#{s3_port_string}/#{attachment.bucket_name}/#{attachment.full_filename}", attachment.s3_url - end - - test_against_subclass :test_should_create_valid_url, S3Attachment - - def test_should_create_authenticated_url(klass = S3Attachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_match /^http.+AWSAccessKeyId.+Expires.+Signature.+/, attachment.authenticated_s3_url(:use_ssl => true) - end - - test_against_subclass :test_should_create_authenticated_url, S3Attachment - - def test_should_create_authenticated_url_for_thumbnail(klass = S3Attachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - ['large', :large].each do |thumbnail| - assert_match( - /^http.+rails_large\.png.+AWSAccessKeyId.+Expires.+Signature/, - attachment.authenticated_s3_url(thumbnail), - "authenticated_s3_url failed with #{thumbnail.class} parameter" - ) - end - end - - def test_should_save_attachment(klass = S3Attachment) - attachment_model klass - assert_created do - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert attachment.image? - assert !attachment.size.zero? - assert_kind_of Net::HTTPOK, http_response_for(attachment.s3_url) - end - end - - test_against_subclass :test_should_save_attachment, S3Attachment - - def test_should_delete_attachment_from_s3_when_attachment_record_destroyed(klass = S3Attachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - - urls = [attachment.s3_url] + attachment.thumbnails.collect(&:s3_url) - - urls.each {|url| assert_kind_of Net::HTTPOK, http_response_for(url) } - attachment.destroy - urls.each do |url| - begin - http_response_for(url) - rescue Net::HTTPForbidden, Net::HTTPNotFound - nil - end - end - end - - test_against_subclass :test_should_delete_attachment_from_s3_when_attachment_record_destroyed, S3Attachment - - protected - def http_response_for(url) - url = URI.parse(url) - Net::HTTP.start(url.host, url.port) {|http| http.request_head(url.path) } - end - - def s3_protocol - Technoweenie::AttachmentFu::Backends::S3Backend.protocol - end - - def s3_hostname - Technoweenie::AttachmentFu::Backends::S3Backend.hostname - end - - def s3_port_string - Technoweenie::AttachmentFu::Backends::S3Backend.port_string - end - else - def test_flunk_s3 - puts "s3 config file not loaded, tests not running" - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/base_attachment_tests.rb b/vendor/plugins/pothoven-attachment_fu/test/base_attachment_tests.rb deleted file mode 100644 index 75fc7e3..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/base_attachment_tests.rb +++ /dev/null @@ -1,77 +0,0 @@ -module BaseAttachmentTests - def test_should_create_file_from_uploaded_file - assert_created do - attachment = upload_file :filename => '/files/foo.txt', :content_type => 'text/plain' - assert_valid attachment - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert !attachment.image? - assert !attachment.size.zero? - #assert_equal 3, attachment.size - assert_nil attachment.width - assert_nil attachment.height - end - end - - def test_should_create_file_from_merb_temp_file - assert_created do - attachment = upload_merb_file :filename => '/files/foo.txt', :content_type => 'text/plain' - assert_valid attachment - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert !attachment.image? - assert !attachment.size.zero? - #assert_equal 3, attachment.size - assert_nil attachment.width - assert_nil attachment.height - end - end - - def test_reassign_attribute_data - assert_created 1 do - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert attachment.size > 0, "no data was set" - - attachment.set_temp_data 'wtf' - assert attachment.save_attachment? - attachment.save! - - assert_equal 'wtf', attachment_model.find(attachment.id).send(:current_data) - end - end - - def test_no_reassign_attribute_data_on_nil - assert_created 1 do - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert attachment.size > 0, "no data was set" - - attachment.set_temp_data nil - assert !attachment.save_attachment? - end - end - - def test_should_overwrite_old_contents_when_updating - attachment = upload_file :filename => '/files/rails.png' - assert_not_created do # no new db_file records - use_temp_file 'files/rails.png' do |file| - attachment.filename = 'rails2.png' - attachment.temp_paths.unshift File.join(FIXTURE_PATH, file) - attachment.save! - end - end - end - - def test_should_save_without_updating_file - attachment = upload_file :filename => '/files/foo.txt' - assert_valid attachment - assert !attachment.save_attachment? - assert_nothing_raised { attachment.save! } - end - - def test_should_handle_nil_file_upload - attachment = attachment_model.create :uploaded_data => '' - assert_raise ActiveRecord::RecordInvalid do - attachment.save! - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/basic_test.rb b/vendor/plugins/pothoven-attachment_fu/test/basic_test.rb deleted file mode 100644 index a0a1ad6..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/basic_test.rb +++ /dev/null @@ -1,121 +0,0 @@ -# -*- coding: utf-8 -*- -require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper')) - -class BasicTest < Test::Unit::TestCase - def test_should_set_default_min_size - assert_equal 1, Attachment.attachment_options[:min_size] - end - - def test_should_set_default_max_size - assert_equal 1.megabyte, Attachment.attachment_options[:max_size] - end - - def test_should_set_default_size - assert_equal (1..1.megabyte), Attachment.attachment_options[:size] - end - - def test_should_set_default_thumbnails_option - assert_equal Hash.new, Attachment.attachment_options[:thumbnails] - end - - def test_should_set_default_thumbnail_class - assert_equal Attachment, Attachment.attachment_options[:thumbnail_class] - end - - def test_should_normalize_content_types_to_array - assert_equal %w(pdf), PdfAttachment.attachment_options[:content_type] - assert_equal %w(pdf doc txt), DocAttachment.attachment_options[:content_type] - assert_equal Technoweenie::AttachmentFu.content_types, ImageAttachment.attachment_options[:content_type] - assert_equal ['pdf'] + Technoweenie::AttachmentFu.content_types, ImageOrPdfAttachment.attachment_options[:content_type] - end - - def test_should_sanitize_content_type - @attachment = Attachment.new :content_type => ' foo ' - assert_equal 'foo', @attachment.content_type - end - - def test_should_sanitize_filenames - @attachment = Attachment.new :filename => 'blah/foo.bar' - assert_equal 'foo.bar', @attachment.filename - - @attachment.filename = 'blah\\foo.bar' - assert_equal 'foo.bar', @attachment.filename - - @attachment.filename = 'f o!O-.bar' - assert_equal 'f_o_O-.bar', @attachment.filename - -# @attachment.filename = 'sheeps_says_bææ' -# assert_equal 'sheeps_says_b__', @attachment.filename - - @attachment.filename = nil - assert_nil @attachment.filename - end - - def test_should_convert_thumbnail_name - @attachment = FileAttachment.new :filename => 'foo.bar' - assert_equal 'foo.bar', @attachment.thumbnail_name_for(nil) - assert_equal 'foo.bar', @attachment.thumbnail_name_for('') - assert_equal 'foo_blah.bar', @attachment.thumbnail_name_for(:blah) - assert_equal 'foo_blah.blah.bar', @attachment.thumbnail_name_for('blah.blah') - - @attachment.filename = 'foo.bar.baz' - assert_equal 'foo.bar_blah.baz', @attachment.thumbnail_name_for(:blah) - end - - def test_should_require_valid_thumbnails_option - klass = Class.new(ActiveRecord::Base) - assert_raise ArgumentError do - klass.has_attachment :thumbnails => [] - end - end - - class ::ImageWithPolymorphicThumbsAttachment - cattr_accessor :thumbnail_creations - - def create_or_update_thumbnail(path, thumb, *size) - @@thumbnail_creations[thumb] = size.size == 1 ? size.first : size - end - - def self.reset_creations - @@thumbnail_creations = {} - end - end - - def test_should_handle_polymorphic_thumbnails_option - assert_polymorphic_thumb_creation nil, - :thumb => [50, 50], :geometry => 'x50' - assert_polymorphic_thumb_creation 'Product', - :thumb => [50, 50], :geometry => 'x50', :large_thumb => '169x169!', :zoomed => '500x500>' - assert_polymorphic_thumb_creation 'Editorial', - :thumb => [50, 50], :geometry => 'x50', :fullsize => '150x100>' - assert_polymorphic_thumb_creation 'User', - :thumb => [50, 50], :geometry => 'x50', :avatar => '64x64!' - end - - def test_should_compute_per_thumbnail_jpeg_quality - assert_jpeg_quality :thumb, 90 - assert_jpeg_quality :avatar, 85 - assert_jpeg_quality :large, 75 - assert_jpeg_quality :large, 0x200 | 75, false - assert_jpeg_quality nil, 75 - end - -private - def assert_jpeg_quality(thumbnail, quality, require_0_to_100 = true) - klass = ImageWithPerThumbJpegAttachment - w, h = if thumbnail - klass.attachment_options[:thumbnails][thumbnail].scan(/\d+/) - else - klass.attachment_options[:resize_to].scan(/\d+/) - end - attachment = klass.new(:thumbnail => thumbnail, :width => w, :height => h) - assert_equal quality, attachment.send(:get_jpeg_quality, require_0_to_100) - end - - def assert_polymorphic_thumb_creation(parent, defs) - attachment_model ImageWithPolymorphicThumbsAttachment - attachment_model.reset_creations - attachment = upload_file :filename => '/files/rails.png', :imageable_type => parent.to_s.classify, :imageable_id => nil - assert_equal defs, attachment_model.thumbnail_creations - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/test/database.yml b/vendor/plugins/pothoven-attachment_fu/test/database.yml deleted file mode 100644 index 3e8ef3e..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/database.yml +++ /dev/null @@ -1,18 +0,0 @@ -sqlite: - :adapter: sqlite - :database: attachment_fu_plugin.sqlite.db -sqlite3: - :adapter: sqlite3 - :database: attachment_fu_plugin.sqlite3.db -postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: attachment_fu_plugin_test - :min_messages: ERROR -mysql: - :adapter: mysql - :host: localhost - :username: rails - :password: - :database: attachment_fu_plugin_test \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/extra_attachment_test.rb b/vendor/plugins/pothoven-attachment_fu/test/extra_attachment_test.rb deleted file mode 100644 index 6c58554..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/extra_attachment_test.rb +++ /dev/null @@ -1,67 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper')) - -class OrphanAttachmentTest < Test::Unit::TestCase - include BaseAttachmentTests - attachment_model OrphanAttachment - - def test_should_create_image_from_uploaded_file - assert_created do - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert attachment.image? - assert !attachment.size.zero? - end - end - - def test_should_create_file_from_uploaded_file - assert_created do - attachment = upload_file :filename => '/files/foo.txt' - assert_valid attachment - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert attachment.image? - assert !attachment.size.zero? - end - end - - def test_should_create_file_from_merb_temp_file - assert_created do - attachment = upload_merb_file :filename => '/files/foo.txt' - assert_valid attachment - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert attachment.image? - assert !attachment.size.zero? - end - end - - def test_should_create_image_from_uploaded_file_with_custom_content_type - assert_created do - attachment = upload_file :content_type => 'foo/bar', :filename => '/files/rails.png' - assert_valid attachment - assert !attachment.image? - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert !attachment.size.zero? - #assert_equal 1784, attachment.size - end - end - - def test_should_create_thumbnail - attachment = upload_file :filename => '/files/rails.png' - - assert_raise Technoweenie::AttachmentFu::ThumbnailError do - attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', 50, 50) - end - end - - def test_should_create_thumbnail_with_geometry_string - attachment = upload_file :filename => '/files/rails.png' - - assert_raise Technoweenie::AttachmentFu::ThumbnailError do - attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', 'x50') - end - end -end - -class MinimalAttachmentTest < OrphanAttachmentTest - attachment_model MinimalAttachment -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/fixtures/attachment.rb b/vendor/plugins/pothoven-attachment_fu/test/fixtures/attachment.rb deleted file mode 100644 index 7c3b32e..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/fixtures/attachment.rb +++ /dev/null @@ -1,297 +0,0 @@ -class Attachment < ActiveRecord::Base - @@saves = 0 - cattr_accessor :saves - has_attachment :processor => :rmagick - validates_as_attachment - after_save do |record| - self.saves += 1 - end -end - -class LowerQualityAttachment < Attachment - self.table_name = 'attachments' - has_attachment :resize_to => [55,55], :jpeg_quality => 50 -end - -class SmallAttachment < Attachment - has_attachment :max_size => 1.kilobyte -end - -class BigAttachment < Attachment - has_attachment :size => 1.megabyte..2.megabytes -end - -class PdfAttachment < Attachment - has_attachment :content_type => 'pdf' -end - -class DocAttachment < Attachment - has_attachment :content_type => %w(pdf doc txt) -end - -class ImageAttachment < Attachment - has_attachment :content_type => :image, :resize_to => [50,50] -end - -class ImageOrPdfAttachment < Attachment - has_attachment :content_type => ['pdf', :image], :resize_to => 'x50' -end - -class ImageWithThumbsAttachment < Attachment - has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }, :resize_to => [55,55] - # after_resize do |record, img| - # record.aspect_ratio = img.columns.to_f / img.rows.to_f - # end -end - -class ImageWithPerThumbJpegAttachment < Attachment - has_attachment :resize_to => '500x500!', - :thumbnails => { :thumb => '50x50!', :large => '300x300!', :avatar => '64x64!' }, - :jpeg_quality => { :thumb => 90, '<5000' => 85, '>=5000' => 75, :large => 0x200 | 75 } -end - -class ImageWithPolymorphicThumbsAttachment < Attachment - belongs_to :imageable, :polymorphic => true - has_attachment :thumbnails => { - :thumb => [50, 50], - :geometry => 'x50', - :products => { :large_thumb => '169x169!', :zoomed => '500x500>' }, - :editorials => { :fullsize => '150x100>' }, - 'User' => { :avatar => '64x64!' } - } -end - -class FileAttachment < ActiveRecord::Base - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick - validates_as_attachment -end - -class FileAttachmentWithStringId < ActiveRecord::Base - self.table_name = 'file_attachments_with_string_id' - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick - validates_as_attachment - - before_validation :auto_generate_id - before_save :auto_generate_id - @@last_id = 0 - - private - def auto_generate_id - @@last_id += 1 - self.id = "id_#{@@last_id}" - end -end - -class FileAttachmentWithUuid < ActiveRecord::Base - self.table_name = 'file_attachments_with_string_id' - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick, :uuid_primary_key => true - validates_as_attachment - - before_validation :auto_generate_id - before_save :auto_generate_id - @@last_id = 0 - - private - def auto_generate_id - @@last_id += 1 - self.id = "%0127dx" % @@last_id - end -end - -class ImageFileAttachment < FileAttachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :content_type => :image, :resize_to => [50,50] -end - -class ImageWithThumbsFileAttachment < FileAttachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }, :resize_to => [55,55] - # after_resize do |record, img| - # record.aspect_ratio = img.columns.to_f / img.rows.to_f - # end -end - -class ImageWithThumbsClassFileAttachment < FileAttachment - # use file_system_path to test backwards compatibility - has_attachment :file_system_path => 'vendor/plugins/attachment_fu/test/files', - :thumbnails => { :thumb => [50, 50] }, :resize_to => [55,55], - :thumbnail_class => 'ImageThumbnail' -end - -class ImageThumbnail < FileAttachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files/thumbnails' -end - -# no parent -class OrphanAttachment < ActiveRecord::Base - has_attachment :processor => :rmagick - validates_as_attachment -end - -# no filename, no size, no content_type -class MinimalAttachment < ActiveRecord::Base - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick - validates_as_attachment - - def filename - "#{id}.file" - end -end - -begin - class ImageScienceAttachment < ActiveRecord::Base - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :image_science, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55 - end - - class ImageScienceLowerQualityAttachment < ActiveRecord::Base - self.table_name = 'image_science_attachments' - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :image_science, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55, - :jpeg_quality => 75 - end - - class ImageScienceWithPerThumbJpegAttachment < ImageScienceAttachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :image_science, - :resize_to => '100x100', - :thumbnails => { :thumb => [50, 50], :editorial => '300x120', :avatar => '64x64!' }, - :jpeg_quality => { :thumb => 90, '<5000' => 80, '>=5000' => 75 } - end -rescue MissingSourceFile - puts $!.message - puts "no ImageScience" -end - -begin - class CoreImageAttachment < ActiveRecord::Base - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :core_image, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55 - end - - class LowerQualityCoreImageAttachment < CoreImageAttachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :core_image, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55, - :jpeg_quality => 50 - end - - class CoreImageWithPerThumbJpegAttachment < CoreImageAttachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :core_image, - :resize_to => '100x100', - :thumbnails => { :thumb => [50, 50], :editorial => '300x120', :avatar => '64x64!' }, - :jpeg_quality => { :thumb => 90, '<5000' => 80, '>=5000' => 75 } - end -rescue MissingSourceFile - puts $!.message - puts "no CoreImage" -end - -begin - class MiniMagickAttachment < ActiveRecord::Base - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :mini_magick, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55 - end - - class ImageThumbnailCrop < MiniMagickAttachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :thumbnails => { :square => "50x50c", :vertical => "30x60c", :horizontal => "60x30c"} - - # TODO this is a bad duplication, this method is in the MiniMagick Processor - def self.calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect) - # only crop if image is not smaller in both dimensions - - # special cases, image smaller in one dimension then thumbsize - if image_width < thumb_width - offset = (image_height / 2) - (thumb_height / 2) - command = "#{image_width}x#{thumb_height}+0+#{offset}" - elsif image_height < thumb_height - offset = (image_width / 2) - (thumb_width / 2) - command = "#{thumb_width}x#{image_height}+#{offset}+0" - - # normal thumbnail generation - # calculate height and offset y, width is fixed - elsif (image_aspect <= thumb_aspect or image_width < thumb_width) and image_height > thumb_height - height = image_width / thumb_aspect - offset = (image_height / 2) - (height / 2) - command = "#{image_width}x#{height}+0+#{offset}" - # calculate width and offset x, height is fixed - else - width = image_height * thumb_aspect - offset = (image_width / 2) - (width / 2) - command = "#{width}x#{image_height}+#{offset}+0" - end - # crop image - command - end - end - - class LowerQualityMiniMagickAttachment < ActiveRecord::Base - self.table_name = 'mini_magick_attachments' - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :mini_magick, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55, - :jpeg_quality => 50 - end - - class MiniMagickWithPerThumbJpegAttachment < MiniMagickAttachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :mini_magick, - :resize_to => '100x100', - :thumbnails => { :thumb => [50, 50], :editorial => '300x120', :avatar => '64x64!' }, - :jpeg_quality => { :thumb => 90, '<5000' => 80, '>=5000' => 75 } - end - -rescue MissingSourceFile - puts $!.message - puts "no Mini Magick" -end - -begin - class GD2Attachment < ActiveRecord::Base - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :gd2, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55 - end - - class LowerQualityGD2Attachment < GD2Attachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :gd2, :thumbnails => { :thumb => [50, 51], :geometry => '31>', :aspect => '25x25!' }, :resize_to => 55, - :jpeg_quality => 50 - end - - class GD2WithPerThumbJpegAttachment < GD2Attachment - has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', - :processor => :gd2, - :resize_to => '100x100', - :thumbnails => { :thumb => [50, 50], :editorial => '300x120', :avatar => '64x64!' }, - :jpeg_quality => { :thumb => 90, '<5000' => 80, '>=5000' => 75 } - end -rescue MissingSourceFile - puts $!.message - puts "no GD2" -end - - -begin - class S3Attachment < ActiveRecord::Base - has_attachment :storage => :s3, :processor => :rmagick, :s3_config_path => File.join(File.dirname(__FILE__), '../amazon_s3.yml') - validates_as_attachment - end - - class CloudFilesAttachment < ActiveRecord::Base - has_attachment :storage => :cloud_files, :processor => :rmagick, :cloudfiles_config_path => File.join(File.dirname(__FILE__), '../rackspace_cloudfiles.yml') - validates_as_attachment - end - - class S3WithPathPrefixAttachment < S3Attachment - has_attachment :storage => :s3, :path_prefix => 'some/custom/path/prefix', :processor => :rmagick - validates_as_attachment - end - - class CloudFilesWithPathPrefixAttachment < CloudFilesAttachment - has_attachment :storage => :cloud_files, :path_prefix => 'some/custom/path/prefix', :processor => :rmagick - validates_as_attachment - end - -rescue - puts "S3 error: #{$!}" -end diff --git a/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/fake/rails.png b/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/fake/rails.png deleted file mode 100644 index 0543c64..0000000 Binary files a/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/fake/rails.png and /dev/null differ diff --git a/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/foo.txt b/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/foo.txt deleted file mode 100644 index 1910281..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/foo.txt +++ /dev/null @@ -1 +0,0 @@ -foo \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/rails.jpg b/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/rails.jpg deleted file mode 100644 index c2a94bc..0000000 Binary files a/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/rails.jpg and /dev/null differ diff --git a/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/rails.png b/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/rails.png deleted file mode 100644 index b8441f1..0000000 Binary files a/vendor/plugins/pothoven-attachment_fu/test/fixtures/files/rails.png and /dev/null differ diff --git a/vendor/plugins/pothoven-attachment_fu/test/geometry_test.rb b/vendor/plugins/pothoven-attachment_fu/test/geometry_test.rb deleted file mode 100644 index c4df31c..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/geometry_test.rb +++ /dev/null @@ -1,114 +0,0 @@ -require 'test/unit' -require File.expand_path(File.join(File.dirname(__FILE__), '../lib/geometry')) unless Object.const_defined?(:Geometry) - -class GeometryTest < Test::Unit::TestCase - def test_should_resize - assert_geometry 50, 64, - "50x50" => [39, 50], - "60x60" => [47, 60], - "100x100" => [78, 100] - end - - def test_should_resize_no_width - assert_geometry 50, 64, - "x50" => [39, 50], - "x60" => [47, 60], - "x100" => [78, 100] - end - - def test_should_resize_no_height - assert_geometry 50, 64, - "50" => [50, 64], - "60" => [60, 77], - "100" => [100, 128] - end - - def test_should_resize_no_height_with_x - assert_geometry 50, 64, - "50x" => [50, 64], - "60x" => [60, 77], - "100x" => [100, 128] - end - - def test_should_resize_with_percent - assert_geometry 50, 64, - "50x50%" => [25, 32], - "60x60%" => [30, 38], - "120x112%" => [60, 72] - end - - def test_should_resize_with_percent_and_no_width - assert_geometry 50, 64, - "x50%" => [50, 32], - "x60%" => [50, 38], - "x112%" => [50, 72] - end - - def test_should_resize_with_percent_and_no_height - assert_geometry 50, 64, - "50%" => [25, 32], - "60%" => [30, 38], - "120%" => [60, 77] - end - - def test_should_resize_with_less - assert_geometry 50, 64, - "50x50<" => [50, 64], - "60x60<" => [50, 64], - "100x100<" => [78, 100], - "100x112<" => [88, 112], - "40x70<" => [50, 64] - end - - def test_should_resize_with_less_and_no_width - assert_geometry 50, 64, - "x50<" => [50, 64], - "x60<" => [50, 64], - "x100<" => [78, 100] - end - - def test_should_resize_with_less_and_no_height - assert_geometry 50, 64, - "50<" => [50, 64], - "60<" => [60, 77], - "100<" => [100, 128] - end - - def test_should_resize_with_greater - assert_geometry 50, 64, - "50x50>" => [39, 50], - "60x60>" => [47, 60], - "100x100>" => [50, 64], - "100x112>" => [50, 64], - "40x70>" => [40, 51] - end - - def test_should_resize_with_greater_and_no_width - assert_geometry 50, 64, - "x40>" => [31, 40], - "x60>" => [47, 60], - "x100>" => [50, 64] - end - - def test_should_resize_with_greater_and_no_height - assert_geometry 50, 64, - "40>" => [40, 51], - "60>" => [50, 64], - "100>" => [50, 64] - end - - def test_should_resize_with_aspect - assert_geometry 50, 64, - "35x35!" => [35, 35], - "70x70!" => [70, 70] - end - - protected - def assert_geometry(width, height, values) - values.each do |geo, result| - # run twice to verify the Geometry string isn't modified after a run - geo = Geometry.from_s(geo) - 2.times { assert_equal result, [width, height] / geo } - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/processors/core_image_test.rb b/vendor/plugins/pothoven-attachment_fu/test/processors/core_image_test.rb deleted file mode 100644 index cf1f662..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/processors/core_image_test.rb +++ /dev/null @@ -1,58 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) - -class CoreImageTest < Test::Unit::TestCase - attachment_model CoreImageAttachment - - if Object.const_defined?(:OSX) - def test_should_resize_image - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert attachment.image? - # test core image thumbnail - assert_equal 42, attachment.width - assert_equal 55, attachment.height - - thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } - geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } - aspect = attachment.thumbnails.detect { |t| t.filename =~ /_aspect/ } - - # test exact resize dimensions - assert_equal 50, thumb.width - assert_equal 51, thumb.height - - # test geometry strings - assert_equal 31, geo.width - assert_equal 41, geo.height - assert_equal 25, aspect.width - assert_equal 25, aspect.height - - # This makes sure that we didn't overwrite the original file - # and will end up with a thumbnail instead of the original - assert_equal 42, attachment.width - assert_equal 55, attachment.height - - end - - def test_should_handle_jpeg_quality - attachment_model CoreImageAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - full_size = attachment.size - attachment_model LowerQualityCoreImageAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - lq_size = attachment.size - assert lq_size <= full_size * 0.9, 'Lower-quality JPEG filesize should be congruently smaller' - - # FIXME: wait for Marcus' reply to determine whether I can get exact-quality output or need to adjust for CoreImage. - # attachment_model CoreImageWithPerThumbJpegAttachment - # attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - # assert_file_jpeg_quality attachment, :thumb, 90 - # assert_file_jpeg_quality attachment, :avatar, 80 - # assert_file_jpeg_quality attachment, :editorial, 75 - # assert_file_jpeg_quality attachment, nil, 75 - end - else - def test_flunk - puts "CoreImage not loaded, tests not running" - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/processors/gd2_test.rb b/vendor/plugins/pothoven-attachment_fu/test/processors/gd2_test.rb deleted file mode 100644 index c6484bf..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/processors/gd2_test.rb +++ /dev/null @@ -1,51 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) - -class GD2Test < Test::Unit::TestCase - attachment_model GD2Attachment - - if Object.const_defined?(:GD2) - def test_should_resize_image - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert attachment.image? - # test gd2 thumbnail - assert_equal 43, attachment.width - assert_equal 55, attachment.height - - thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } - geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } - aspect = attachment.thumbnails.detect { |t| t.filename =~ /_aspect/ } - - # test exact resize dimensions - assert_equal 50, thumb.width - assert_equal 51, thumb.height - - # test geometry strings - assert_equal 31, geo.width - assert_equal 40, geo.height - assert_equal 25, aspect.width - assert_equal 25, aspect.height - end - - def test_should_handle_jpeg_quality - attachment_model GD2Attachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - full_size = attachment.size - attachment_model LowerQualityGD2Attachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - lq_size = attachment.size - assert lq_size <= full_size * 0.9, 'Lower-quality JPEG filesize should be congruently smaller' - - attachment_model GD2WithPerThumbJpegAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - assert_file_jpeg_quality attachment, :thumb, 90 - assert_file_jpeg_quality attachment, :avatar, 80 - assert_file_jpeg_quality attachment, :editorial, 75 - assert_file_jpeg_quality attachment, nil, 75 - end - else - def test_flunk - puts "GD2 not loaded, tests not running" - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/processors/image_science_test.rb b/vendor/plugins/pothoven-attachment_fu/test/processors/image_science_test.rb deleted file mode 100644 index 2b04277..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/processors/image_science_test.rb +++ /dev/null @@ -1,54 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) - -class ImageScienceTest < Test::Unit::TestCase - attachment_model ImageScienceAttachment - - if Object.const_defined?(:ImageScience) - def test_should_resize_image - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert attachment.image? - # test image science thumbnail - assert_equal 42, attachment.width - assert_equal 55, attachment.height - - thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } - geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } - aspect = attachment.thumbnails.detect { |t| t.filename =~ /_aspect/ } - - # test exact resize dimensions - assert_equal 50, thumb.width - assert_equal 51, thumb.height - - # test geometry strings - assert_equal 31, geo.width - assert_equal 41, geo.height - assert_equal 25, aspect.width - assert_equal 25, aspect.height - end - - def test_should_handle_jpeg_quality - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - full_size = attachment.size - attachment_model ImageScienceLowerQualityAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - lq_size = attachment.size - if ImageScience.instance_method(:save).arity == -2 # tdd-image_science: JPEG quality processing - assert lq_size <= full_size * 0.75, 'Lower-quality JPEG filesize should be congruently smaller' - else - assert_equal full_size, lq_size, 'Unsupported lower-quality JPEG should yield exact same file size' - end - - attachment_model ImageScienceWithPerThumbJpegAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - assert_file_jpeg_quality attachment, :thumb, 90 - assert_file_jpeg_quality attachment, :avatar, 80 - assert_file_jpeg_quality attachment, :editorial, 75 - assert_file_jpeg_quality attachment, nil, 75 - end - else - def test_flunk - puts "ImageScience not loaded, tests not running" - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/test/processors/mini_magick_test.rb b/vendor/plugins/pothoven-attachment_fu/test/processors/mini_magick_test.rb deleted file mode 100644 index 12e621f..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/processors/mini_magick_test.rb +++ /dev/null @@ -1,122 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) - -class MiniMagickTest < Test::Unit::TestCase - attachment_model MiniMagickAttachment - - if Object.const_defined?(:MiniMagick) - def test_should_resize_image - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert attachment.image? - # test MiniMagick thumbnail - assert_equal 43, attachment.width - assert_equal 55, attachment.height - - thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } - geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } - aspect = attachment.thumbnails.detect { |t| t.filename =~ /_aspect/ } - - # test exact resize dimensions - assert_equal 50, thumb.width - assert_equal 51, thumb.height - - # test geometry strings - assert_equal 31, geo.width - assert_equal 40, geo.height - assert_equal 25, aspect.width - assert_equal 25, aspect.height - end - - def test_should_crop_image(klass = ImageThumbnailCrop) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert attachment.image? - # has_attachment :thumbnails => { :square => "50x50c", :vertical => "30x60c", :horizontal => "60x30c"} - - square = attachment.thumbnails.detect { |t| t.filename =~ /_square/ } - vertical = attachment.thumbnails.detect { |t| t.filename =~ /_vertical/ } - horizontal = attachment.thumbnails.detect { |t| t.filename =~ /_horizontal/ } - - # test excat resize - assert_equal 50, square.width - assert_equal 50, square.height - - assert_equal 30, vertical.width - assert_equal 60, vertical.height - - assert_equal 60, horizontal.width - assert_equal 30, horizontal.height - end - - # tests the first step in resize, crop the image in original size to right format - def test_should_crop_image_right(klass = ImageThumbnailCrop) - @@testcases.collect do |testcase| - image_width, image_height, thumb_width, thumb_height = testcase[:data] - image_aspect, thumb_aspect = image_width/image_height, thumb_width/thumb_height - crop_comand = klass.calculate_offset(image_width, image_height, image_aspect, thumb_width, thumb_height,thumb_aspect) - # pattern matching on crop command - if testcase.has_key?(:height) - assert crop_comand.match(/^#{image_width}x#{testcase[:height]}\+0\+#{testcase[:yoffset]}$/) - else - assert crop_comand.match(/^#{testcase[:width]}x#{image_height}\+#{testcase[:xoffset]}\+0$/) - end - end - end - - def test_should_handle_jpeg_quality - attachment_model MiniMagickAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - full_size = attachment.size - attachment_model LowerQualityMiniMagickAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - lq_size = attachment.size - assert lq_size <= full_size * 0.9, 'Lower-quality JPEG filesize should be congruently smaller' - - attachment_model MiniMagickWithPerThumbJpegAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - assert_file_jpeg_quality attachment, :thumb, 90 - assert_file_jpeg_quality attachment, :avatar, 80 - assert_file_jpeg_quality attachment, :editorial, 75 - assert_file_jpeg_quality attachment, nil, 75 - end - else - def test_flunk - puts "MiniMagick not loaded, tests not running" - end - end - - @@testcases = [ - # image_aspect <= 1 && thumb_aspect >= 1 - {:data => [10.0,40.0,2.0,1.0], :height => 5.0, :yoffset => 17.5}, # 1b - {:data => [10.0,40.0,1.0,1.0], :height => 10.0, :yoffset => 15.0}, # 1b - - # image_aspect < 1 && thumb_aspect < 1 - {:data => [10.0,40.0,1.0,2.0], :height => 20.0, :yoffset => 10.0}, # 1a - {:data => [2.0,3.0,1.0,2.0], :width => 1.5, :xoffset => 0.25}, # 1a - - # image_aspect = thumb_aspect - {:data => [10.0,10.0,1.0,1.0], :height => 10.0, :yoffset => 0.0}, # QUADRAT 1c - - # image_aspect >= 1 && thumb_aspect > 1 && image_aspect < thumb_aspect - {:data => [6.0,3.0,4.0,1.0], :height => 1.5, :yoffset => 0.75}, # 2b - {:data => [6.0,6.0,4.0,1.0], :height => 1.5, :yoffset => 2.25}, # 2b - - # image_aspect > 1 && thumb_aspect > 1 && image_aspect > thumb_aspect - {:data => [9.0,3.0,2.0,1.0], :width => 6.0, :xoffset => 1.5}, # 2a - - # image_aspect > 1 && thumb_aspect < 1 && image_aspect < thumb_aspect - {:data => [10.0,5.0,0.1,2.0], :width => 0.25, :xoffset => 4.875}, # 4 - {:data => [10.0,5.0,1.0,2.0], :width => 2.5, :xoffset => 3.75}, # 4 - - # image_aspect > 1 && thumb_aspect > 1 && image_aspect > thumb_aspect - {:data => [9.0,3.0,2.0,1.0], :width => 6.0, :xoffset => 1.5}, # 3a - # image_aspect > 1 && thumb_aspect > 1 && image_aspect < thumb_aspect - {:data => [9.0,3.0,5.0,1.0], :height => 1.8, :yoffset => 0.6} # 3a - ] - - - - - -end diff --git a/vendor/plugins/pothoven-attachment_fu/test/processors/rmagick_test.rb b/vendor/plugins/pothoven-attachment_fu/test/processors/rmagick_test.rb deleted file mode 100644 index 1571dcb..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/processors/rmagick_test.rb +++ /dev/null @@ -1,272 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) -class RmagickTest < Test::Unit::TestCase - attachment_model Attachment - - if Object.const_defined?(:Magick) - def test_should_create_image_from_uploaded_file - assert_created do - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert attachment.image? - assert !attachment.size.zero? - #assert_equal 1784, attachment.size - assert_equal 50, attachment.width - assert_equal 64, attachment.height - assert_equal '50x64', attachment.image_size - end - end - - def test_should_create_image_from_uploaded_file_with_custom_content_type - assert_created do - attachment = upload_file :content_type => 'foo/bar', :filename => '/files/rails.png' - assert_valid attachment - assert !attachment.image? - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert !attachment.size.zero? - #assert_equal 1784, attachment.size - assert_nil attachment.width - assert_nil attachment.height - assert_equal [], attachment.thumbnails - end - end - - def test_should_create_thumbnail - attachment = upload_file :filename => '/files/rails.png' - - assert_created do - basename, ext = attachment.filename.split '.' - thumbnail = attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', 50, 50) - assert_valid thumbnail - assert !thumbnail.size.zero? - #assert_in_delta 4673, thumbnail.size, 2 - assert_equal 50, thumbnail.width - assert_equal 50, thumbnail.height - assert_equal [thumbnail.id], attachment.thumbnails.collect(&:id) - assert_equal attachment.id, thumbnail.parent_id if thumbnail.respond_to?(:parent_id) - assert_equal "#{basename}_thumb.#{ext}", thumbnail.filename - end - end - - def test_should_create_thumbnail_with_geometry_strings - attachment = upload_file :filename => '/files/rails.png' - - assert_created do - basename, ext = attachment.filename.split '.' - { 'x50' => [39, 50], '25x25!' => [25, 25] }.each do |geo, (w, h)| - thumbnail = attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', geo) - assert_valid thumbnail - assert !thumbnail.size.zero? - assert_equal w, thumbnail.width - assert_equal h, thumbnail.height - assert_equal [thumbnail], attachment.thumbnails - assert_equal attachment.id, thumbnail.parent_id if thumbnail.respond_to?(:parent_id) - assert_equal "#{basename}_thumb.#{ext}", thumbnail.filename - end - end - end - - def test_should_resize_image(klass = ImageAttachment) - attachment_model klass - assert_equal [50, 50], attachment_model.attachment_options[:resize_to] - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert attachment.image? - assert !attachment.size.zero? - #assert_in_delta 4673, attachment.size, 2 - assert_equal 50, attachment.width - assert_equal 50, attachment.height - end - - test_against_subclass :test_should_resize_image, ImageAttachment - - def test_should_resize_image_with_geometry(klass = ImageOrPdfAttachment) - attachment_model klass - assert_equal 'x50', attachment_model.attachment_options[:resize_to] - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) - assert attachment.image? - assert !attachment.size.zero? - #assert_equal 3915, attachment.size - assert_equal 39, attachment.width - assert_equal 50, attachment.height - end - - test_against_subclass :test_should_resize_image_with_geometry, ImageOrPdfAttachment - - def test_should_give_correct_thumbnail_filenames(klass = ImageWithThumbsFileAttachment) - attachment_model klass - assert_created 3 do - attachment = upload_file :filename => '/files/rails.png' - thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } - geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } - - [attachment, thumb, geo].each { |record| assert_valid record } - - assert_match /rails\.png$/, attachment.full_filename - assert_match /rails_geometry\.png$/, attachment.full_filename(:geometry) - assert_match /rails_thumb\.png$/, attachment.full_filename(:thumb) - end - end - - test_against_subclass :test_should_give_correct_thumbnail_filenames, ImageWithThumbsFileAttachment - - def test_should_automatically_create_thumbnails(klass = ImageWithThumbsAttachment) - attachment_model klass - assert_created 3 do - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - assert !attachment.size.zero? - #assert_equal 1784, attachment.size - assert_equal 55, attachment.width - assert_equal 55, attachment.height - assert_equal 2, attachment.thumbnails.length - # assert_equal 1.0, attachment.aspect_ratio - - thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } - assert !thumb.new_record?, thumb.errors.full_messages.join("\n") - assert !thumb.size.zero? - #assert_in_delta 4673, thumb.size, 2 - assert_equal 50, thumb.width - assert_equal 50, thumb.height - # assert_equal 1.0, thumb.aspect_ratio - - geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } - assert !geo.new_record?, geo.errors.full_messages.join("\n") - assert !geo.size.zero? - #assert_equal 3915, geo.size - assert_equal 50, geo.width - assert_equal 50, geo.height - # assert_equal 1.0, geo.aspect_ratio - end - end - - test_against_subclass :test_should_automatically_create_thumbnails, ImageWithThumbsAttachment - - # same as above method, but test it on a file model - test_against_class :test_should_automatically_create_thumbnails, ImageWithThumbsFileAttachment - test_against_subclass :test_should_automatically_create_thumbnails_on_class, ImageWithThumbsFileAttachment - - def test_should_use_thumbnail_subclass(klass = ImageWithThumbsClassFileAttachment) - attachment_model klass - attachment = nil - assert_difference ImageThumbnail, :count do - attachment = upload_file :filename => '/files/rails.png' - assert_valid attachment - end - assert_kind_of ImageThumbnail, attachment.thumbnails.first - if attachment.thumbnails.first.respond_to?(:parent) - assert_equal attachment.id, attachment.thumbnails.first.parent.id - assert_kind_of FileAttachment, attachment.thumbnails.first.parent - end - assert_equal 'rails_thumb.png', attachment.thumbnails.first.filename - assert_equal attachment.thumbnails.first.full_filename, attachment.full_filename(attachment.thumbnails.first.thumbnail), - "#full_filename does not use thumbnail class' path." - assert_equal attachment.destroy, attachment - end - - test_against_subclass :test_should_use_thumbnail_subclass, ImageWithThumbsClassFileAttachment - - def test_should_remove_old_thumbnail_files_when_updating(klass = ImageWithThumbsFileAttachment) - attachment_model klass - attachment = nil - assert_created 3 do - attachment = upload_file :filename => '/files/rails.png' - end - - old_filenames = [attachment.full_filename] + attachment.thumbnails.collect(&:full_filename) - - assert_not_created do - use_temp_file "files/rails.png" do |file| - attachment.filename = 'rails2.png' - attachment.temp_paths.unshift File.join(FIXTURE_PATH, file) - attachment.save - new_filenames = [attachment.reload.full_filename] + attachment.thumbnails.collect { |t| t.reload.full_filename } - new_filenames.each { |f| assert File.exists?(f), "#{f} does not exist" } - old_filenames.each { |f| assert !File.exists?(f), "#{f} still exists" } - end - end - end - - test_against_subclass :test_should_remove_old_thumbnail_files_when_updating, ImageWithThumbsFileAttachment - - def test_should_delete_file_when_in_file_system_when_attachment_record_destroyed(klass = ImageWithThumbsFileAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - filenames = [attachment.full_filename] + attachment.thumbnails.collect(&:full_filename) - filenames.each { |f| assert File.exists?(f), "#{f} never existed to delete on destroy" } - attachment.destroy - filenames.each { |f| assert !File.exists?(f), "#{f} still exists" } - end - - test_against_subclass :test_should_delete_file_when_in_file_system_when_attachment_record_destroyed, ImageWithThumbsFileAttachment - - def test_should_have_full_filename_method(klass = FileAttachment) - attachment_model klass - attachment = upload_file :filename => '/files/rails.png' - assert_respond_to attachment, :full_filename - end - - test_against_subclass :test_should_have_full_filename_method, FileAttachment - - def test_should_overwrite_old_thumbnail_records_when_updating(klass = ImageWithThumbsAttachment) - attachment_model klass - attachment = nil - assert_created 3 do - attachment = upload_file :filename => '/files/rails.png' - end - assert_not_created do # no new db_file records - use_temp_file "files/rails.png" do |file| - attachment.filename = 'rails2.png' - # The above test (#test_should_have_full_filename_method) to pass before be can set the temp_path below -- - # #temp_path calls #full_filename, which is not getting mixed into the attachment. Maybe we don't need to - # set temp_path at all? - # - # attachment.temp_paths.unshift File.join(FIXTURE_PATH, file) - attachment.save! - end - end - end - - test_against_subclass :test_should_overwrite_old_thumbnail_records_when_updating, ImageWithThumbsAttachment - - def test_should_overwrite_old_thumbnail_records_when_renaming(klass = ImageWithThumbsAttachment) - attachment_model klass - attachment = nil - assert_created 3 do - attachment = upload_file :class => klass, :filename => '/files/rails.png' - end - assert_not_created do # no new db_file records - attachment.filename = 'rails2.png' - attachment.save - assert !attachment.reload.size.zero? - assert_equal 'rails2.png', attachment.filename - end - end - - test_against_subclass :test_should_overwrite_old_thumbnail_records_when_renaming, ImageWithThumbsAttachment - - def test_should_handle_jpeg_quality - attachment_model ImageWithThumbsAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - full_size = attachment.size - attachment_model LowerQualityAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - lq_size = attachment.size - assert lq_size <= full_size * 0.9, 'Lower-quality JPEG filesize should be congruently smaller' - - attachment_model ImageWithPerThumbJpegAttachment - attachment = upload_file :filename => '/files/rails.jpg', :content_type => 'image/jpeg' - assert_file_jpeg_quality attachment, :thumb, 90 - assert_file_jpeg_quality attachment, :avatar, 85 - assert_file_jpeg_quality attachment, :large, 75 - assert_file_jpeg_quality attachment, nil, 75 - end - else - def test_flunk - puts "RMagick not installed, no tests running" - end - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/test/schema.rb b/vendor/plugins/pothoven-attachment_fu/test/schema.rb deleted file mode 100644 index 12fff6c..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/schema.rb +++ /dev/null @@ -1,136 +0,0 @@ -ActiveRecord::Schema.define(:version => 0) do - create_table :attachments, :force => true do |t| - t.column :db_file_id, :integer - t.column :parent_id, :integer - t.column :imageable_id, :integer - t.column :imageable_type, :string, :limit => 255 - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :aspect_ratio, :float - end - - create_table :file_attachments, :force => true do |t| - t.column :parent_id, :integer - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :type, :string - t.column :aspect_ratio, :float - end - - create_table :file_attachments_with_string_id, :id => false, :force => true do |t| - t.column :id, :string - t.column :parent_id, :string - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :type, :string - t.column :aspect_ratio, :float - end - - create_table :gd2_attachments, :force => true do |t| - t.column :parent_id, :integer - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :type, :string - end - - create_table :image_science_attachments, :force => true do |t| - t.column :parent_id, :integer - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :type, :string - end - - create_table :core_image_attachments, :force => true do |t| - t.column :parent_id, :integer - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :type, :string - end - - create_table :mini_magick_attachments, :force => true do |t| - t.column :parent_id, :integer - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :type, :string - end - - create_table :mini_magick_attachments, :force => true do |t| - t.column :parent_id, :integer - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :type, :string - end - - create_table :orphan_attachments, :force => true do |t| - t.column :db_file_id, :integer - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - end - - create_table :minimal_attachments, :force => true do |t| - t.column :size, :integer - t.column :content_type, :string, :limit => 255 - end - - create_table :db_files, :force => true do |t| - t.column :data, :binary - end - - create_table :s3_attachments, :force => true do |t| - t.column :parent_id, :integer - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :type, :string - t.column :aspect_ratio, :float - end - - create_table :cloud_files_attachments, :force => true do |t| - t.column :parent_id, :integer - t.column :thumbnail, :string - t.column :filename, :string, :limit => 255 - t.column :content_type, :string, :limit => 255 - t.column :size, :integer - t.column :width, :integer - t.column :height, :integer - t.column :type, :string - t.column :aspect_ratio, :float - end - -end diff --git a/vendor/plugins/pothoven-attachment_fu/test/test_helper.rb b/vendor/plugins/pothoven-attachment_fu/test/test_helper.rb deleted file mode 100644 index 7747641..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/test_helper.rb +++ /dev/null @@ -1,169 +0,0 @@ -$LOAD_PATH.unshift(File.dirname(__FILE__)) -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) - -ENV['RAILS_ENV'] = 'test' - -require 'rails/all' -require 'test/unit' -require 'pothoven-attachment_fu' -include ActionDispatch::TestProcess - -# Define the application and configuration -module RbConfig - class Application < ::Rails::Application - # configuration here if needed - config.active_support.deprecation = :stderr - end -end - -# Initialize the application -RbConfig::Application.initialize! - -# Setup database -load(File.dirname(__FILE__) + "/schema.rb") - -FIXTURE_PATH = File.dirname(__FILE__) + "/fixtures" -$LOAD_PATH.unshift(FIXTURE_PATH) - -class Test::Unit::TestCase #:nodoc: - # include ActionDispatch::TestProcess - def create_fixtures(*table_names) - if block_given? - Fixtures.create_fixtures(FIXTURE_PATH, table_names) { yield } - else - Fixtures.create_fixtures(FIXTURE_PATH, table_names) - end - end - - def setup - Attachment.saves = 0 - DbFile.transaction { [Attachment, FileAttachment, OrphanAttachment, MinimalAttachment, DbFile].each { |klass| klass.delete_all } } - attachment_model self.class.attachment_model - end - - def teardown - FileUtils.rm_rf File.join(File.dirname(__FILE__), 'files') - # Files generated by random_tempfile_filename - FileUtils.rm_rf Dir['[0-9]*.{png,jpg}'] - end - - #self.use_transactional_fixtures = true - #self.use_instantiated_fixtures = false - - def self.attachment_model(klass = nil) - @attachment_model = klass if klass - @attachment_model - end - - def self.test_against_class(test_method, klass, subclass = false) - define_method("#{test_method}_on_#{:sub if subclass}class") do - klass = Class.new(klass) if subclass - attachment_model klass - send test_method, klass - end - end - - def self.test_against_subclass(test_method, klass) - test_against_class test_method, klass, true - end - - protected - def upload_file(options = {}) - use_temp_file options[:filename] do |file| -puts options - opts = { :uploaded_data => fixture_file_upload(file, options[:content_type] || 'image/png') } - opts.update(options.reject { |k, v| ![:imageable_type, :imageable_id].include?(k) }) - att = attachment_model.create opts - att.reload unless att.new_record? - return att - end - end - - def upload_merb_file(options = {}) - use_temp_file options[:filename] do |file| - att = attachment_model.create :uploaded_data => {"size" => file.size, "content_type" => options[:content_type] || 'image/png', "filename" => file, 'tempfile' => fixture_file_upload(file, options[:content_type] || 'image/png')} - att.reload unless att.new_record? - return att - end - end - - def use_temp_file(fixture_filename) - temp_path = File.join('/tmp', File.basename(fixture_filename)) - temp_dir = File.join(FIXTURE_PATH, 'tmp') - use_file = File.join(FIXTURE_PATH, temp_path) - FileUtils.mkdir_p temp_dir - FileUtils.cp File.join(FIXTURE_PATH, fixture_filename), use_file - yield use_file - ensure - FileUtils.rm_rf temp_dir - end - - def assert_created(num = 1) - assert_difference attachment_model.base_class, :count, num do - if attachment_model.included_modules.include? DbFile - assert_difference DbFile, :count, num do - yield - end - else - yield - end - end - end - - def assert_valid(record) - assert record.valid?, record.errors.full_messages.join("\n") - end - - def assert_file_jpeg_quality(model, thumbnail, expected) - filename = if model.respond_to?(:full_filename) - model.full_filename(thumbnail) - else - thumb = thumbnail ? model.thumbnails.find(:first, :conditions => { :thumbnail => thumbnail.to_s }, :include => :db_file) : model - unless thumb && thumb.db_file && thumb.db_file.data && thumb.db_file.data.size > 0 - STDERR.puts "Cannot find DB file data for thumbnail #{thumbnail.inspect} -> Aborting JPEG quality check." - return - end - result = Tempfile.new('dbfile_dump').path - File.open(result, 'wb') { |f| f.write(thumb.db_file.data) } - result - end - quality = %x(identify -format '%Q' "#{filename}" 2> /dev/null) - if $?.success? - assert_equal expected, quality.to_i, "Produced JPEG quality (thumbnail: #{thumbnail.inspect}) is incorrect." - else - STDERR.puts "ImageMagick's identify not found / not in PATH: can't quickly check produced image quality." - end - end - - def assert_not_created - assert_created(0) { yield } - end - - def should_reject_by_size_with(klass) - attachment_model klass - assert_not_created do - attachment = upload_file :filename => '/files/rails.png' - assert attachment.new_record? - assert attachment.errors.on(:size) - assert_nil attachment.db_file if attachment.respond_to?(:db_file) - end - end - - def assert_difference(object, method = nil, difference = 1) - initial_value = object.send(method) - yield - assert_equal initial_value + difference, object.send(method) - end - - def assert_no_difference(object, method, &block) - assert_difference object, method, 0, &block - end - - def attachment_model(klass = nil) - @attachment_model = klass if klass - @attachment_model - end -end - -require File.join(File.dirname(__FILE__), 'fixtures/attachment') -require File.join(File.dirname(__FILE__), 'base_attachment_tests') diff --git a/vendor/plugins/pothoven-attachment_fu/test/validation_test.rb b/vendor/plugins/pothoven-attachment_fu/test/validation_test.rb deleted file mode 100644 index cf56c1b..0000000 --- a/vendor/plugins/pothoven-attachment_fu/test/validation_test.rb +++ /dev/null @@ -1,55 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper')) - -class ValidationTest < Test::Unit::TestCase - def test_should_invalidate_big_files - @attachment = SmallAttachment.new - assert !@attachment.valid? - assert @attachment.errors[:size] - - @attachment.size = 2000 - assert !@attachment.valid? - assert @attachment.errors[:size], @attachment.errors.full_messages.to_sentence - - @attachment.size = 1000 - assert !@attachment.valid? - assert @attachment.errors[:size].empty? - end - - def test_should_invalidate_small_files - @attachment = BigAttachment.new - assert !@attachment.valid? - assert @attachment.errors[:size] - - @attachment.size = 2000 - assert !@attachment.valid? - assert @attachment.errors[:size], @attachment.errors.full_messages.to_sentence - - @attachment.size = 1.megabyte - assert !@attachment.valid? - assert @attachment.errors[:size].empty? - end - - def test_should_validate_content_type - @attachment = PdfAttachment.new - assert !@attachment.valid? - assert @attachment.errors[:content_type] - - @attachment.content_type = 'foo' - assert !@attachment.valid? - assert @attachment.errors[:content_type] - - @attachment.content_type = 'pdf' - assert !@attachment.valid? - assert @attachment.errors[:content_type].empty? - end - - def test_should_require_filename - @attachment = Attachment.new - assert !@attachment.valid? - assert @attachment.errors[:filename] - - @attachment.filename = 'foo' - assert !@attachment.valid? - assert @attachment.errors[:filename].empty? - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/color.rb b/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/color.rb deleted file mode 100644 index f593b90..0000000 --- a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/color.rb +++ /dev/null @@ -1,27 +0,0 @@ -module RedArtisan - module CoreImage - module Filters - module Color - - def greyscale(color = nil, intensity = 1.00) - create_core_image_context(@original.extent.size.width, @original.extent.size.height) - - color = OSX::CIColor.colorWithString("1.0 1.0 1.0 1.0") unless color - - @original.color_monochrome :inputColor => color, :inputIntensity => intensity do |greyscale| - @target = greyscale - end - end - - def sepia(intensity = 1.00) - create_core_image_context(@original.extent.size.width, @original.extent.size.height) - - @original.sepia_tone :inputIntensity => intensity do |sepia| - @target = sepia - end - end - - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/effects.rb b/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/effects.rb deleted file mode 100644 index 2e0f244..0000000 --- a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/effects.rb +++ /dev/null @@ -1,31 +0,0 @@ -module RedArtisan - module CoreImage - module Filters - module Effects - - def spotlight(position, points_at, brightness, concentration, color) - create_core_image_context(@original.extent.size.width, @original.extent.size.height) - - @original.spot_light :inputLightPosition => vector3(*position), :inputLightPointsAt => vector3(*points_at), - :inputBrightness => brightness, :inputConcentration => concentration, :inputColor => color do |spot| - @target = spot - end - end - - def edges(intensity = 1.00) - create_core_image_context(@original.extent.size.width, @original.extent.size.height) - - @original.edges :inputIntensity => intensity do |edged| - @target = edged - end - end - - private - - def vector3(x, y, w) - OSX::CIVector.vectorWithX_Y_Z(x, y, w) - end - end - end - end -end diff --git a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb b/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb deleted file mode 100644 index 6160dd8..0000000 --- a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb +++ /dev/null @@ -1,25 +0,0 @@ -module RedArtisan - module CoreImage - module Filters - module Perspective - - def perspective(top_left, top_right, bottom_left, bottom_right) - create_core_image_context(@original.extent.size.width, @original.extent.size.height) - - @original.perspective_transform :inputTopLeft => top_left, :inputTopRight => top_right, :inputBottomLeft => bottom_left, :inputBottomRight => bottom_right do |transformed| - @target = transformed - end - end - - def perspective_tiled(top_left, top_right, bottom_left, bottom_right) - create_core_image_context(@original.extent.size.width, @original.extent.size.height) - - @original.perspective_tile :inputTopLeft => top_left, :inputTopRight => top_right, :inputBottomLeft => bottom_left, :inputBottomRight => bottom_right do |tiled| - @target = tiled - end - end - - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/quality.rb b/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/quality.rb deleted file mode 100644 index 018690f..0000000 --- a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/quality.rb +++ /dev/null @@ -1,25 +0,0 @@ -module RedArtisan - module CoreImage - module Filters - module Quality - - def reduce_noise(level = 0.02, sharpness = 0.4) - create_core_image_context(@original.extent.size.width, @original.extent.size.height) - - @original.noise_reduction :inputNoiseLevel => level, :inputSharpness => sharpness do |noise_reduced| - @target = noise_reduced - end - end - - def adjust_exposure(input_ev = 0.5) - create_core_image_context(@original.extent.size.width, @original.extent.size.height) - - @original.exposure_adjust :inputEV => input_ev do |adjusted| - @target = adjusted - end - end - - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/scale.rb b/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/scale.rb deleted file mode 100644 index f729b59..0000000 --- a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/scale.rb +++ /dev/null @@ -1,47 +0,0 @@ -module RedArtisan - module CoreImage - module Filters - module Scale - - def resize(width, height) - create_core_image_context(width, height) - - scale_x, scale_y = scale(width, height) - - @original.affine_clamp :inputTransform => OSX::NSAffineTransform.transform do |clamped| - clamped.lanczos_scale_transform :inputScale => scale_x > scale_y ? scale_x : scale_y, :inputAspectRatio => scale_x / scale_y do |scaled| - scaled.crop :inputRectangle => vector(0, 0, width, height) do |cropped| - @target = cropped - end - end - end - end - - def thumbnail(width, height) - create_core_image_context(width, height) - - transform = OSX::NSAffineTransform.transform - transform.scaleXBy_yBy *scale(width, height) - - @original.affine_transform :inputTransform => transform do |scaled| - @target = scaled - end - end - - def fit(size) - original_size = @original.extent.size - scale = size.to_f / (original_size.width > original_size.height ? original_size.width : original_size.height) - resize (original_size.width * scale).to_i, (original_size.height * scale).to_i - end - - private - - def scale(width, height) - original_size = @original.extent.size - return width.to_f / original_size.width.to_f, height.to_f / original_size.height.to_f - end - - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb b/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb deleted file mode 100644 index 3c3a1ad..0000000 --- a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb +++ /dev/null @@ -1,32 +0,0 @@ -module RedArtisan - module CoreImage - module Filters - module Watermark - - def watermark(watermark_image, tile = false, strength = 0.1) - create_core_image_context(@original.extent.size.width, @original.extent.size.height) - - if watermark_image.respond_to? :to_str - watermark_image = OSX::CIImage.from(watermark_image.to_str) - end - - if tile - tile_transform = OSX::NSAffineTransform.transform - tile_transform.scaleXBy_yBy 1.0, 1.0 - - watermark_image.affine_tile :inputTransform => tile_transform do |tiled| - tiled.crop :inputRectangle => vector(0, 0, @original.extent.size.width, @original.extent.size.height) do |tiled_watermark| - watermark_image = tiled_watermark - end - end - end - - @original.dissolve_transition :inputTargetImage => watermark_image, :inputTime => strength do |watermarked| - @target = watermarked - end - end - - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/processor.rb b/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/processor.rb deleted file mode 100644 index 965e70c..0000000 --- a/vendor/plugins/pothoven-attachment_fu/vendor/red_artisan/core_image/processor.rb +++ /dev/null @@ -1,123 +0,0 @@ -require 'rubygems' -require 'osx/cocoa' -require 'active_support' - -require 'red_artisan/core_image/filters/scale' -require 'red_artisan/core_image/filters/color' -require 'red_artisan/core_image/filters/watermark' -require 'red_artisan/core_image/filters/quality' -require 'red_artisan/core_image/filters/perspective' -require 'red_artisan/core_image/filters/effects' - -# Generic image processor for scaling images based on CoreImage via RubyCocoa. -# -# Example usage: -# -# p = Processor.new OSX::CIImage.from(path_to_image) -# p.resize(640, 480) -# p.render do |result| -# result.save('resized.jpg', OSX::NSJPEGFileType) -# end -# -# This will resize the image to the given dimensions exactly, if you'd like to ensure that aspect ratio is preserved: -# -# p = Processor.new OSX::CIImage.from(path_to_image) -# p.fit(640) -# p.render do |result| -# result.save('resized.jpg', OSX::NSJPEGFileType) -# end -# -# fit(size) will attempt its best to resize the image so that the longest width/height (depending on image orientation) will match -# the given size. The second axis will be calculated automatically based on the aspect ratio. -# -# Scaling is performed by first clamping the image so that its external bounds become infinite, this helps when scaling so that any -# rounding discrepencies in dimensions don't affect the resultant image. We then perform a Lanczos transform on the image which scales -# it to the target size. We then crop the image to the traget dimensions. -# -# If you are generating smaller images such as thumbnails where high quality rendering isn't as important, an additional method is -# available: -# -# p = Processor.new OSX::CIImage.from(path_to_image) -# p.thumbnail(100, 100) -# p.render do |result| -# result.save('resized.jpg', OSX::NSJPEGFileType) -# end -# -# This will perform a straight affine transform and scale the X and Y boundaries to the requested size. Generally, this will be faster -# than a lanczos scale transform, but with a scaling quality trade. -# -# More than welcome to intregrate any patches, improvements - feel free to mail me with ideas. -# -# Thanks to -# * Satoshi Nakagawa for working out that OCObjWrapper needs inclusion when aliasing method_missing on existing OSX::* classes. -# * Vasantha Crabb for general help and inspiration with Cocoa -# * Ben Schwarz for example image data and collaboration during performance testing -# -# Copyright (c) Marcus Crafter released under the MIT license -# -module RedArtisan - module CoreImage - class Processor - - def initialize(original) - if original.respond_to? :to_str - @original = OSX::CIImage.from(original.to_str) - else - @original = original - end - end - - def render(&block) - raise "unprocessed image: #{@original}" unless @target - block.call @target - end - - include Filters::Scale, Filters::Color, Filters::Watermark, Filters::Quality, Filters::Perspective, Filters::Effects - - private - - def create_core_image_context(width, height) - output = OSX::NSBitmapImageRep.alloc.initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(nil, width, height, 8, 4, true, false, OSX::NSDeviceRGBColorSpace, 0, 0) - context = OSX::NSGraphicsContext.graphicsContextWithBitmapImageRep(output) - OSX::NSGraphicsContext.setCurrentContext(context) - @ci_context = context.CIContext - end - - def vector(x, y, w, h) - OSX::CIVector.vectorWithX_Y_Z_W(x, y, w, h) - end - end - end -end - -module OSX - class CIImage - include OCObjWrapper - - def method_missing_with_filter_processing(sym, *args, &block) - f = OSX::CIFilter.filterWithName("CI#{sym.to_s.camelize}") - return method_missing_without_filter_processing(sym, *args, &block) unless f - - f.setDefaults if f.respond_to? :setDefaults - f.setValue_forKey(self, 'inputImage') - options = args.last.is_a?(Hash) ? args.last : {} - options.each { |k, v| f.setValue_forKey(v, k.to_s) } - - block.call f.valueForKey('outputImage') - end - - alias_method_chain :method_missing, :filter_processing - - def save(target, format = OSX::NSJPEGFileType, properties = nil) - bitmapRep = OSX::NSBitmapImageRep.alloc.initWithCIImage(self) - blob = bitmapRep.representationUsingType_properties(format, properties) - blob.writeToFile_atomically(target, false) - end - - def self.from(filepath) - raise Errno::ENOENT, "No such file or directory - #{filepath}" unless File.exists?(filepath) - OSX::CIImage.imageWithContentsOfURL(OSX::NSURL.fileURLWithPath(filepath)) - end - end -end - -- libgit2 0.21.2