Grosse MàJ

This commit is contained in:
olivier
2008-11-25 22:11:16 +01:00
parent 53195fdfcd
commit 3e719157ea
2980 changed files with 343846 additions and 0 deletions

View File

@ -0,0 +1,19 @@
* 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]

View File

@ -0,0 +1,162 @@
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 three storage options for files uploaded through attachment_fu:
File system
Database file
Amazon S3
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 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.
# 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 # Specifies the storage system to use..
# Defaults to :db_file. Options are :file_system, :db_file, and :s3.
:processor # Sets the image processor to use for resizing of the attached image.
# Options include ImageScience, Rmagick, and MiniMagick. Default is whatever is installed.
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
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 and s3 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

View File

@ -0,0 +1,22 @@
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
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_files.include('lib/**/*.rb')
end

View File

@ -0,0 +1,14 @@
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
access_key_id:
secret_access_key:

View File

@ -0,0 +1,14 @@
require 'tempfile'
Tempfile.class_eval do
# overwrite so tempfiles use the extension of the basename. important for rmagick and image science
def make_tmpname(basename, n)
ext = nil
sprintf("%s%d-%d%s", basename.to_s.gsub(/\.\w+$/) { |s| ext = s; '' }, $$, n, ext)
end
end
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

View File

@ -0,0 +1,5 @@
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)
puts IO.read(File.join(File.dirname(__FILE__), 'README'))

View File

@ -0,0 +1,93 @@
# This Geometry class was yanked from RMagick. However, it lets ImageMagick handle the actual change_geometry.
# Use #new_dimensions_for to get new dimensons
# Used so I can use spiffy RMagick geometry strings with ImageScience
class Geometry
# ! and @ are 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 :<, :>, 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 }
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

View File

@ -0,0 +1,405 @@
module Technoweenie # :nodoc:
module AttachmentFu # :nodoc:
@@default_processors = %w(ImageScience Rmagick MiniMagick)
@@tempfile_path = File.join(RAILS_ROOT, 'tmp', 'attachment_fu')
@@content_types = ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg']
mattr_reader :content_types, :tempfile_path, :default_processors
mattr_writer :tempfile_path
class ThumbnailError < StandardError; end
class AttachmentError < StandardError; end
module ActMethods
# Options:
# * <tt>:content_type</tt> - Allowed content types. Allows all by default. Use :image to allow all standard image types.
# * <tt>:min_size</tt> - Minimum size allowed. 1 byte is the default.
# * <tt>:max_size</tt> - Maximum size allowed. 1.megabyte is the default.
# * <tt>:size</tt> - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
# * <tt>:resize_to</tt> - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string.
# * <tt>:thumbnails</tt> - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and RMagick resizing options.
# * <tt>:thumbnail_class</tt> - Set what class to use for thumbnails. This attachment class is used by default.
# * <tt>:path_prefix</tt> - 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.
# * <tt>:storage</tt> - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system.
#
# 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[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil?
unless options[:thumbnails].is_a?(Hash)
raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
end
# doing these shenanigans so that #attachment_options is available to processors and backends
class_inheritable_accessor :attachment_options
self.attachment_options = options
# only need to define these once on a class
unless included_modules.include?(InstanceMethods)
attr_accessor :thumbnail_resize_options
attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
if attachment_options[:path_prefix].nil?
attachment_options[:path_prefix] = attachment_options[:storage] == :s3 ? table_name : File.join("public", table_name)
end
attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
with_options :foreign_key => 'parent_id' do |m|
m.has_many :thumbnails, :class_name => attachment_options[:thumbnail_class].to_s
m.belongs_to :parent, :class_name => base_class.to_s
end
before_destroy :destroy_thumbnails
before_validation :set_size_from_temp_path
after_save :after_process_attachment
after_destroy :destroy_file
extend ClassMethods
include InstanceMethods
include Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend")
case attachment_options[:processor]
when :none
when nil
processors = Technoweenie::AttachmentFu.default_processors.dup
begin
include Technoweenie::AttachmentFu::Processors.const_get("#{processors.first}Processor") if processors.any?
rescue LoadError, MissingSourceFile
processors.shift
retry
end
else
begin
include Technoweenie::AttachmentFu::Processors.const_get("#{options[:processor].to_s.classify}Processor")
rescue LoadError, MissingSourceFile
puts "Problems loading #{options[:processor]}Processor: #{$!}"
end
end
after_validation :process_attachment
end
end
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
# 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 |record, thumbnail|
# ...
# end
# end
def before_thumbnail_saved(&block)
write_inheritable_array(:before_thumbnail_saved, [block])
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)
returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) 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)
returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
tmp.binmode
tmp.write data
tmp.close
end
end
end
module InstanceMethods
# 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)
return filename if thumbnail.blank?
ext = nil
basename = filename.gsub /\.\w+$/ do |s|
ext = s; ''
end
"#{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"))
returning find_or_initialize_thumbnail(file_name_suffix) do |thumb|
thumb.attributes = {
:content_type => content_type,
:filename => thumbnail_name_for(file_name_suffix),
:temp_path => temp_file,
:thumbnail_resize_options => size
}
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.to_s)
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| -%>
# <p><%= f.file_field :uploaded_data %></p>
# <p><%= submit_tag :Save %>
# <% end -%>
#
# @attachment = Attachment.create! params[:attachment]
#
# TODO: Allow it to work with Merb tempfiles too.
def uploaded_data=(file_data)
return nil if file_data.nil? || file_data.size == 0
self.content_type = file_data.content_type
self.filename = file_data.original_filename if respond_to?(:filename)
if file_data.is_a?(StringIO)
file_data.rewind
self.temp_data = file_data.read
else
self.temp_path = 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? || !File.exist?(full_filename)) ? [] : [copy_to_temp_file(full_filename)]
end
# Adds a new temp_path to the array. This should take a string or a Tempfile. This class makes no
# attempt to remove the files, so Tempfiles should be used. Tempfiles remove themselves when they go out of scope.
# You can also use string paths for temporary files, such as those used for uploaded files in a web server.
def temp_path=(value)
temp_paths.unshift value
temp_path
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 temp_data=(data)
self.temp_path = 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
"#{rand Time.now.to_i}#{filename || 'attachment'}"
end
def sanitize_filename(filename)
returning filename.strip 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! /[^\w\.\-]/, '_'
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]
errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
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) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil?
temp_file = temp_path || create_temp_file
attachment_options[:thumbnails].each { |suffix, size| create_or_update_thumbnail(temp_file, suffix, *size) }
end
save_to_storage
@temp_paths.clear
@saved_attachment = nil
callback :after_attachment_saved
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
# Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self.
# Only accept blocks, however
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
return result
end
# Removes the thumbnails for the attachment, if it has any
def destroy_thumbnails
self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
end
end
end
end

View File

@ -0,0 +1,39 @@
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

View File

@ -0,0 +1,97 @@
require 'ftools'
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).to_i
end
# overrwrite this to do your own app-specific partitioning.
# you can thank Jamis Buck for this: http://www.37signals.com/svn/archives2/id_partitioning.php
def partitioned_path(*args)
("%08d" % attachment_path_id).scan(/..../) + args
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))
File.cp(temp_path, full_filename)
File.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

View File

@ -0,0 +1,309 @@
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 <tt>RAILS_ROOT/config/amazon_s3.yml</tt> and is loaded according to the <tt>RAILS_ENV</tt>.
# 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.
#
# Example configuration (RAILS_ROOT/config/amazon_s3.yml)
#
# development:
# bucket_name: appname_development
# access_key_id: <your key>
# secret_access_key: <your key>
#
# test:
# bucket_name: appname_test
# access_key_id: <your key>
# secret_access_key: <your key>
#
# production:
# bucket_name: appname
# access_key_id: <your key>
# secret_access_key: <your key>
#
# 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
#
# * <tt>:access_key_id</tt> - The access key id for your S3 account. Provided by Amazon.
# * <tt>:secret_access_key</tt> - The secret access key for your S3 account. Provided by Amazon.
# * <tt>:bucket_name</tt> - 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
#
# * <tt>:server</tt> - The server to make requests to. Defaults to <tt>s3.amazonaws.com</tt>.
# * <tt>:port</tt> - The port to the requests should be made on. Defaults to 80 or 443 if <tt>:use_ssl</tt> is set.
# * <tt>:use_ssl</tt> - If set to true, <tt>:port</tt> will be implicitly set to 443, unless specified otherwise. Defaults to false.
#
# == Usage
#
# To specify S3 as the storage mechanism for a model, set the acts_as_attachment <tt>:storage</tt> option to <tt>:s3</tt>.
#
# 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 <tt>:table_name/:id</tt>, 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 <tt>:path_prefix</tt>
# option:
#
# class Photo < ActiveRecord::Base
# has_attachment :storage => :s3, :path_prefix => 'my/custom/path'
# end
#
# Which would result in URLs like <tt>http(s)://:server/:bucket_name/my/custom/path/:id/:filename.</tt>
#
# === Permissions
#
# By default, files are stored on S3 with public access permissions. You can customize this using
# the <tt>:s3_access</tt> option to <tt>has_attachment</tt>. Available values are
# <tt>:private</tt>, <tt>:public_read_write</tt>, and <tt>:authenticated_read</tt>.
#
# === 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
# <tt>base_path</tt>:
#
# @photo.file_base_path # => photos/1
#
# And the full path (including the filename) using <tt>full_filename</tt>:
#
# @photo.full_filename # => photos/
#
# Niether <tt>base_path</tt> or <tt>full_filename</tt> include the bucket name as part of the path.
# You can retrieve the bucket name using the <tt>bucket_name</tt> method.
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] || (RAILS_ROOT + '/config/amazon_s3.yml')
@@s3_config = YAML.load_file(@@s3_config_path)[ENV['RAILS_ENV']].symbolize_keys
#rescue
# raise ConfigFileNotFoundError.new('File %s not found' % @@s3_config_path)
end
@@bucket_name = s3_config[:bucket_name]
Base.establish_connection!(
:access_key_id => s3_config[:access_key_id],
:secret_access_key => s3_config[:secret_access_key],
:server => s3_config[:server],
:port => s3_config[:port],
:use_ssl => s3_config[:use_ssl]
)
# 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] == (s3_config[:use_ssl] ? 443 : 80) ? '' : ":#{s3_config[:port]}"
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
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: <tt>:table_name/:id</tt>
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: <tt>:table_name/:id/:filename</tt>
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: <tt>http(s)://:server/:bucket_name/:table_name/:id/:file</tt> where
# the <tt>:server</tt> variable defaults to <tt>AWS::S3 URL::DEFAULT_HOST</tt> (s3.amazonaws.com) and can be
# set using the configuration parameters in <tt>RAILS_ROOT/config/amazon_s3.yml</tt>.
#
# 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
alias :public_filename :s3_url
# 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 <tt>:expires</tt> option,
# or with a number of seconds relative to now with the <tt>:expires_in</tt> 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 <tt>:use_ssl</tt> 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)
thumbnail = args.first.is_a?(String) ? args.first : nil
options = args.last.is_a?(Hash) ? args.last : {}
S3Object.url_for(full_filename(thumbnail), bucket_name, options)
end
def create_temp_file
write_to_temp_file current_data
end
def current_data
S3Object.value full_filename, bucket_name
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
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?
S3Object.store(
full_filename,
(temp_path ? File.open(temp_path) : temp_data),
bucket_name,
:content_type => content_type,
:access => attachment_options[:s3_access]
)
end
@old_filename = nil
true
end
end
end
end
end

View File

@ -0,0 +1,55 @@
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 RMagick 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
filename.sub! /gif$/, 'png'
self.temp_path = 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)
img.save 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
img.resize(new_size[0], new_size[1], &grab_dimensions)
end
end
end
end
end
end

View File

@ -0,0 +1,56 @@
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.from_file(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
if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
if size.is_a?(Fixnum)
size = [size, size]
img.resize(size.join('x'))
else
img.resize(size.join('x') + '!')
end
else
img.resize(size.to_s)
end
self.temp_path = img
end
end
end
end
end

View File

@ -0,0 +1,53 @@
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)
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)
else
img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols, rows) }
end
self.temp_path = write_to_temp_file(img.to_blob)
end
end
end
end
end

View File

@ -0,0 +1,6 @@
test:
bucket_name: afu
access_key_id: YOURACCESSKEY
secret_access_key: YOURSECRETACCESSKEY
server: 127.0.0.1
port: 3002

View File

@ -0,0 +1,16 @@
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

View File

@ -0,0 +1,80 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
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_path = 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
end

View File

@ -0,0 +1,103 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper'))
require 'net/http'
class S3Test < Test::Unit::TestCase
if 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_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

View File

@ -0,0 +1,57 @@
module BaseAttachmentTests
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?
#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.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.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_path = 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
end

View File

@ -0,0 +1,64 @@
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 ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png'], ImageAttachment.attachment_options[:content_type]
assert_equal ['pdf', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png'], 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
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
end

View File

@ -0,0 +1,18 @@
sqlite:
:adapter: sqlite
:dbfile: attachment_fu_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
:dbfile: 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

View File

@ -0,0 +1,57 @@
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_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

View File

@ -0,0 +1,127 @@
class Attachment < ActiveRecord::Base
@@saves = 0
cattr_accessor :saves
has_attachment :processor => :rmagick
validates_as_attachment
after_attachment_saved do |record|
self.saves += 1
end
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 FileAttachment < ActiveRecord::Base
has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick
validates_as_attachment
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>' }, :resize_to => 55
end
rescue MissingSourceFile
puts $!.message
puts "no ImageScience"
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>' }, :resize_to => 55
end
rescue MissingSourceFile
puts $!.message
puts "no Mini Magick"
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>' }, :resize_to => 55
end
rescue MissingSourceFile
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 S3WithPathPrefixAttachment < S3Attachment
has_attachment :storage => :s3, :path_prefix => 'some/custom/path/prefix', :processor => :rmagick
validates_as_attachment
end
rescue Technoweenie::AttachmentFu::Backends::S3Backend::ConfigFileNotFoundError
puts "S3 error: #{$!}"
end

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -0,0 +1,101 @@
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_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
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

View File

@ -0,0 +1,31 @@
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/ }
# test exact resize dimensions
assert_equal 50, thumb.width
assert_equal 51, thumb.height
# test geometry string
assert_equal 31, geo.width
assert_equal 41, geo.height
end
else
def test_flunk
puts "ImageScience not loaded, tests not running"
end
end
end

View File

@ -0,0 +1,31 @@
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/ }
# test exact resize dimensions
assert_equal 50, thumb.width
assert_equal 51, thumb.height
# test geometry string
assert_equal 31, geo.width
assert_equal 40, geo.height
end
else
def test_flunk
puts "MiniMagick not loaded, tests not running"
end
end
end

View File

@ -0,0 +1,241 @@
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_string
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', 'x50')
assert_valid thumbnail
assert !thumbnail.size.zero?
#assert_equal 3915, thumbnail.size
assert_equal 39, thumbnail.width
assert_equal 50, 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
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
assert_equal attachment.id, attachment.thumbnails.first.parent.id
assert_kind_of FileAttachment, attachment.thumbnails.first.parent
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_path = 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_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'
attachment.temp_path = 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
else
def test_flunk
puts "RMagick not installed, no tests running"
end
end
end

View File

@ -0,0 +1,86 @@
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 :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 :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 :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
end

View File

@ -0,0 +1,142 @@
$:.unshift(File.dirname(__FILE__) + '/../lib')
ENV['RAILS_ENV'] = 'test'
require 'test/unit'
require File.expand_path(File.join(File.dirname(__FILE__), '../../../../config/environment.rb'))
require 'breakpoint'
require 'active_record/fixtures'
require 'action_controller/test_process'
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
db_adapter = ENV['DB']
# no db passed, try one of these fine config-free DBs before bombing.
db_adapter ||=
begin
require 'rubygems'
require 'sqlite'
'sqlite'
rescue MissingSourceFile
begin
require 'sqlite3'
'sqlite3'
rescue MissingSourceFile
end
end
if db_adapter.nil?
raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
end
ActiveRecord::Base.establish_connection(config[db_adapter])
load(File.dirname(__FILE__) + "/schema.rb")
Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures"
$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path)
class Test::Unit::TestCase #:nodoc:
include ActionController::TestProcess
def create_fixtures(*table_names)
if block_given?
Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) { yield }
else
Fixtures.create_fixtures(Test::Unit::TestCase.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')
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|
att = attachment_model.create :uploaded_data => 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))
FileUtils.mkdir_p File.join(fixture_path, 'tmp')
FileUtils.cp File.join(fixture_path, fixture_filename), File.join(fixture_path, temp_path)
yield temp_path
ensure
FileUtils.rm_rf File.join(fixture_path, 'tmp')
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_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')

View File

@ -0,0 +1,55 @@
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.on(:size)
@attachment.size = 2000
assert !@attachment.valid?
assert @attachment.errors.on(:size), @attachment.errors.full_messages.to_sentence
@attachment.size = 1000
assert !@attachment.valid?
assert_nil @attachment.errors.on(:size)
end
def test_should_invalidate_small_files
@attachment = BigAttachment.new
assert !@attachment.valid?
assert @attachment.errors.on(:size)
@attachment.size = 2000
assert !@attachment.valid?
assert @attachment.errors.on(:size), @attachment.errors.full_messages.to_sentence
@attachment.size = 1.megabyte
assert !@attachment.valid?
assert_nil @attachment.errors.on(:size)
end
def test_should_validate_content_type
@attachment = PdfAttachment.new
assert !@attachment.valid?
assert @attachment.errors.on(:content_type)
@attachment.content_type = 'foo'
assert !@attachment.valid?
assert @attachment.errors.on(:content_type)
@attachment.content_type = 'pdf'
assert !@attachment.valid?
assert_nil @attachment.errors.on(:content_type)
end
def test_should_require_filename
@attachment = Attachment.new
assert !@attachment.valid?
assert @attachment.errors.on(:filename)
@attachment.filename = 'foo'
assert !@attachment.valid?
assert_nil @attachment.errors.on(:filename)
end
end

View File

@ -0,0 +1,12 @@
= MysqlTasks
Some rake tasks to automate common database tasks (create/destroy & backup/restore).
== Components
rake db:mysql:create # Create database (using database.yml config)
rake db:mysql:destroy # Destroy database (using database.yml config)
rake db:mysql:backup # Dump schema and data to an SQL file (/db/backup_YYYY_MM_DD.sql)
rake db:mysql:restore # Load schema and data from an SQL file (/db/restore.sql)
Specifying RAILS_ENV works if you want to perform operations on test or production databases.

View File

@ -0,0 +1,59 @@
namespace :db do
namespace :mysql do
desc "Dump schema and data to an SQL file (/db/backup_YYYY_MM_DD.sql)"
task :backup => :environment do
current_date = Time.now.strftime("%Y_%m_%d")
archive = "#{RAILS_ROOT}/db/backup_#{current_date}.sql"
database, user, password = retrieve_db_info
cmd = "/usr/bin/env mysqldump --opt --skip-add-locks -u#{user} "
puts cmd + "... [password filtered]"
cmd += " -p'#{password}' " unless password.nil?
cmd += " #{database} > #{archive}"
result = system(cmd)
end
desc "Load schema and data from an SQL file (/db/restore.sql)"
task :restore => :environment do
archive = "#{RAILS_ROOT}/db/restore.sql"
database, user, password = retrieve_db_info
cmd = "/usr/bin/env mysql -u #{user} #{database} < #{archive}"
puts cmd + "... [password filtered]"
cmd += " -p'#{password}'"
result = system(cmd)
end
desc "Create database (using database.yml config)"
task :create => :environment do
database, user, password = retrieve_db_info
sql = "CREATE DATABASE #{database};"
sql += "GRANT ALL PRIVILEGES ON #{database}.* TO #{user}@localhost IDENTIFIED BY '#{password}';"
mysql_execute(user, password, sql)
end
desc "Destroy database (using database.yml config)"
task :destroy => :environment do
database, user, password = retrieve_db_info
sql = "DROP DATABASE #{database};"
mysql_execute(user, password, sql)
end
end
end
private
def retrieve_db_info
result = File.read "#{RAILS_ROOT}/config/database.yml"
result.strip!
config_file = YAML::load(ERB.new(result).result)
return [
config_file[RAILS_ENV]['database'],
config_file[RAILS_ENV]['username'],
config_file[RAILS_ENV]['password']
]
end
def mysql_execute(username, password, sql)
system("/usr/bin/env mysql -u #{username} -p'#{password}' --execute=\"#{sql}\"")
end

View File

@ -0,0 +1,29 @@
Restful Authentication Generator
====
This is a basic restful authentication generator for rails, taken from acts as authenticated. Currently it requires Rails 1.2 (or edge).
To use:
./script/generate authenticated user sessions --include-activation
The first parameter specifies the model that gets created in signup (typically a user or account model). A model with migration is created, as well as a basic controller with the create method.
The second parameter specifies the sessions controller name. This is the controller that handles the actual login/logout function on the site.
The third parameter (--include-activation) generates the code for a ActionMailer and its respective Activation Code through email.
You can pass --skip-migration to skip the user migration.
From here, you will need to add the resource routes in config/routes.rb.
map.resources :users
map.resource :session
If you're on rails 1.2.3 you may need to specify the controller name for the session singular resource:
map.resource :session, :controller => 'sessions'
Also, add an observer to config/environment.rb if you chose the --include-activation option
config.active_record.observers = :user_observer # or whatever you named your model

View File

@ -0,0 +1,22 @@
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
desc 'Default: run unit tests.'
task :default => :test
desc 'Test the restful_authentication plugin.'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end
desc 'Generate documentation for the restful_authentication plugin.'
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'RestfulAuthentication'
rdoc.options << '--line-numbers' << '--inline-source'
rdoc.rdoc_files.include('README')
rdoc.rdoc_files.include('lib/**/*.rb')
end

View File

@ -0,0 +1 @@
./script/generate authenticated USERMODEL CONTROLLERNAME

View File

@ -0,0 +1,218 @@
class AuthenticatedGenerator < Rails::Generator::NamedBase
attr_reader :controller_name,
:controller_class_path,
:controller_file_path,
:controller_class_nesting,
:controller_class_nesting_depth,
:controller_class_name,
:controller_singular_name,
:controller_plural_name
alias_method :controller_file_name, :controller_singular_name
alias_method :controller_table_name, :controller_plural_name
attr_reader :model_controller_name,
:model_controller_class_path,
:model_controller_file_path,
:model_controller_class_nesting,
:model_controller_class_nesting_depth,
:model_controller_class_name,
:model_controller_singular_name,
:model_controller_plural_name
alias_method :model_controller_file_name, :model_controller_singular_name
alias_method :model_controller_table_name, :model_controller_plural_name
def initialize(runtime_args, runtime_options = {})
super
@controller_name = args.shift || 'sessions'
@model_controller_name = @name.pluralize
# sessions controller
base_name, @controller_class_path, @controller_file_path, @controller_class_nesting, @controller_class_nesting_depth = extract_modules(@controller_name)
@controller_class_name_without_nesting, @controller_singular_name, @controller_plural_name = inflect_names(base_name)
if @controller_class_nesting.empty?
@controller_class_name = @controller_class_name_without_nesting
else
@controller_class_name = "#{@controller_class_nesting}::#{@controller_class_name_without_nesting}"
end
# model controller
base_name, @model_controller_class_path, @model_controller_file_path, @model_controller_class_nesting, @model_controller_class_nesting_depth = extract_modules(@model_controller_name)
@model_controller_class_name_without_nesting, @model_controller_singular_name, @model_controller_plural_name = inflect_names(base_name)
if @model_controller_class_nesting.empty?
@model_controller_class_name = @model_controller_class_name_without_nesting
else
@model_controller_class_name = "#{@model_controller_class_nesting}::#{@model_controller_class_name_without_nesting}"
end
end
def manifest
recorded_session = record do |m|
# Check for class naming collisions.
m.class_collisions controller_class_path, "#{controller_class_name}Controller", # Sessions Controller
"#{controller_class_name}Helper"
m.class_collisions model_controller_class_path, "#{model_controller_class_name}Controller", # Model Controller
"#{model_controller_class_name}Helper"
m.class_collisions class_path, "#{class_name}", "#{class_name}Mailer", "#{class_name}MailerTest", "#{class_name}Observer"
m.class_collisions [], 'AuthenticatedSystem', 'AuthenticatedTestHelper'
# Controller, helper, views, and test directories.
m.directory File.join('app/models', class_path)
m.directory File.join('app/controllers', controller_class_path)
m.directory File.join('app/controllers', model_controller_class_path)
m.directory File.join('app/helpers', controller_class_path)
m.directory File.join('app/views', controller_class_path, controller_file_name)
m.directory File.join('app/views', class_path, "#{file_name}_mailer") if options[:include_activation]
m.directory File.join('test/functional', controller_class_path)
m.directory File.join('app/controllers', model_controller_class_path)
m.directory File.join('app/helpers', model_controller_class_path)
m.directory File.join('app/views', model_controller_class_path, model_controller_file_name)
m.directory File.join('test/functional', model_controller_class_path)
m.directory File.join('test/unit', class_path)
m.template 'model.rb',
File.join('app/models',
class_path,
"#{file_name}.rb")
if options[:include_activation]
%w( mailer observer ).each do |model_type|
m.template "#{model_type}.rb", File.join('app/models',
class_path,
"#{file_name}_#{model_type}.rb")
end
end
m.template 'controller.rb',
File.join('app/controllers',
controller_class_path,
"#{controller_file_name}_controller.rb")
m.template 'model_controller.rb',
File.join('app/controllers',
model_controller_class_path,
"#{model_controller_file_name}_controller.rb")
m.template 'authenticated_system.rb',
File.join('lib', 'authenticated_system.rb')
m.template 'authenticated_test_helper.rb',
File.join('lib', 'authenticated_test_helper.rb')
m.template 'functional_test.rb',
File.join('test/functional',
controller_class_path,
"#{controller_file_name}_controller_test.rb")
m.template 'model_functional_test.rb',
File.join('test/functional',
model_controller_class_path,
"#{model_controller_file_name}_controller_test.rb")
m.template 'helper.rb',
File.join('app/helpers',
controller_class_path,
"#{controller_file_name}_helper.rb")
m.template 'model_helper.rb',
File.join('app/helpers',
model_controller_class_path,
"#{model_controller_file_name}_helper.rb")
m.template 'unit_test.rb',
File.join('test/unit',
class_path,
"#{file_name}_test.rb")
if options[:include_activation]
m.template 'mailer_test.rb', File.join('test/unit', class_path, "#{file_name}_mailer_test.rb")
end
m.template 'fixtures.yml',
File.join('test/fixtures',
"#{table_name}.yml")
# Controller templates
m.template 'login.rhtml', File.join('app/views', controller_class_path, controller_file_name, "new.rhtml")
m.template 'signup.rhtml', File.join('app/views', model_controller_class_path, model_controller_file_name, "new.rhtml")
if options[:include_activation]
# Mailer templates
%w( activation signup_notification ).each do |action|
m.template "#{action}.rhtml",
File.join('app/views', "#{file_name}_mailer", "#{action}.rhtml")
end
end
unless options[:skip_migration]
m.migration_template 'migration.rb', 'db/migrate', :assigns => {
:migration_name => "Create#{class_name.pluralize.gsub(/::/, '')}"
}, :migration_file_name => "create_#{file_path.gsub(/\//, '_').pluralize}"
end
end
action = nil
action = $0.split("/")[1]
case action
when "generate"
puts
puts ("-" * 70)
puts "Don't forget to:"
puts
puts " - add restful routes in config/routes.rb"
puts " map.resources :#{model_controller_file_name}"
puts " map.resource :#{controller_singular_name.singularize}"
puts
puts " Rails 1.2.3 may need a :controller option for the singular resource:"
puts " - map.resource :#{controller_singular_name.singularize}, :controller => '#{controller_file_name}'"
puts
if options[:include_activation]
puts " map.activate '/activate/:activation_code', :controller => '#{model_controller_file_name}', :action => 'activate'"
puts
puts " - add an observer to config/environment.rb"
puts " config.active_record.observers = :#{file_name}_observer"
end
puts
puts "Try these for some familiar login URLs if you like:"
puts
puts " map.signup '/signup', :controller => '#{model_controller_file_name}', :action => 'new'"
puts " map.login '/login', :controller => '#{controller_file_name}', :action => 'new'"
puts " map.logout '/logout', :controller => '#{controller_file_name}', :action => 'destroy'"
puts
puts ("-" * 70)
puts
when "destroy"
puts
puts ("-" * 70)
puts
puts "Thanks for using restful_authentication"
puts
puts "Don't forget to comment out the observer line in environment.rb"
puts " (This was optional so it may not even be there)"
puts " # config.active_record.observers = :#{file_name}_observer"
puts
puts ("-" * 70)
puts
else
puts
end
recorded_session
end
protected
# Override with your own usage banner.
def banner
"Usage: #{$0} authenticated ModelName [ControllerName]"
end
def add_options!(opt)
opt.separator ''
opt.separator 'Options:'
opt.on("--skip-migration",
"Don't generate a migration file for this model") { |v| options[:skip_migration] = v }
opt.on("--include-activation",
"Generate signup 'activation code' confirmation via email") { |v| options[:include_activation] = v }
end
end

View File

@ -0,0 +1,3 @@
<%%= @<%= file_name %>.login %>, your account has been activated. You may now start adding your plugins:
<%%= @url %>

View File

@ -0,0 +1,127 @@
module AuthenticatedSystem
protected
# Returns true or false if the user is logged in.
# Preloads @current_<%= file_name %> with the user model if they're logged in.
def logged_in?
current_<%= file_name %> != :false
end
# Accesses the current <%= file_name %> from the session. Set it to :false if login fails
# so that future calls do not hit the database.
def current_<%= file_name %>
@current_user ||= (login_from_session || login_from_basic_auth || login_from_cookie || :false)
end
# Store the given <%= file_name %> in the session.
def current_<%= file_name %>=(new_<%= file_name %>)
session[:<%= file_name %>] = (new_<%= file_name %>.nil? || new_<%= file_name %>.is_a?(Symbol)) ? nil : new_<%= file_name %>.id
@current_<%= file_name %> = new_<%= file_name %>
end
# Check if the <%= file_name %> is authorized
#
# Override this method in your controllers if you want to restrict access
# to only a few actions or if you want to check if the <%= file_name %>
# has the correct rights.
#
# Example:
#
# # only allow nonbobs
# def authorized?
# current_<%= file_name %>.login != "bob"
# end
def authorized?
logged_in?
end
# Filter method to enforce a login requirement.
#
# To require logins for all actions, use this in your controllers:
#
# before_filter :login_required
#
# To require logins for specific actions, use this in your controllers:
#
# before_filter :login_required, :only => [ :edit, :update ]
#
# To skip this in a subclassed controller:
#
# skip_before_filter :login_required
#
def login_required
authorized? || access_denied
end
# Redirect as appropriate when an access request fails.
#
# The default action is to redirect to the login screen.
#
# Override this method in your controllers if you want to have special
# behavior in case the <%= file_name %> is not authorized
# to access the requested action. For example, a popup window might
# simply close itself.
def access_denied
respond_to do |accepts|
accepts.html do
store_location
redirect_to :controller => '/<%= controller_file_name %>', :action => 'new'
end
accepts.xml do
headers["Status"] = "Unauthorized"
headers["WWW-Authenticate"] = %(Basic realm="Web Password")
render :text => "Could't authenticate you", :status => '401 Unauthorized'
end
end
false
end
# Store the URI of the current request in the session.
#
# We can return to this location by calling #redirect_back_or_default.
def store_location
session[:return_to] = request.request_uri
end
# Redirect to the URI stored by the most recent store_location call or
# to the passed default.
def redirect_back_or_default(default)
session[:return_to] ? redirect_to_url(session[:return_to]) : redirect_to(default)
session[:return_to] = nil
end
# Inclusion hook to make #current_<%= file_name %> and #logged_in?
# available as ActionView helper methods.
def self.included(base)
base.send :helper_method, :current_<%= file_name %>, :logged_in?
end
# Called from #current_user. First attempt to login by the user id stored in the session.
def login_from_session
self.current_<%= file_name %> = <%= class_name %>.find_by_id(session[:<%= file_name %>]) if session[:<%= file_name %>]
end
# Called from #current_user. Now, attempt to login by basic authentication information.
def login_from_basic_auth
username, passwd = get_auth_data
self.current_<%= file_name %> = <%= class_name %>.authenticate(username, passwd) if username && passwd
end
# Called from #current_user. Finaly, attempt to login by an expiring token in the cookie.
def login_from_cookie
<%= file_name %> = cookies[:auth_token] && <%= class_name %>.find_by_remember_token(cookies[:auth_token])
if <%= file_name %> && <%= file_name %>.remember_token?
<%= file_name %>.remember_me
cookies[:auth_token] = { :value => <%= file_name %>.remember_token, :expires => <%= file_name %>.remember_token_expires_at }
self.current_<%= file_name %> = <%= file_name %>
end
end
private
@@http_auth_headers = %w(X-HTTP_AUTHORIZATION HTTP_AUTHORIZATION Authorization)
# gets BASIC auth info
def get_auth_data
auth_key = @@http_auth_headers.detect { |h| request.env.has_key?(h) }
auth_data = request.env[auth_key].to_s.split unless auth_key.blank?
return auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil]
end
end

View File

@ -0,0 +1,26 @@
module AuthenticatedTestHelper
# Sets the current <%= file_name %> in the session from the <%= file_name %> fixtures.
def login_as(<%= file_name %>)
@request.session[:<%= file_name %>] = <%= file_name %> ? <%= table_name %>(<%= file_name %>).id : nil
end
def authorize_as(user)
@request.env["HTTP_AUTHORIZATION"] = user ? "Basic #{Base64.encode64("#{users(user).login}:test")}" : nil
end
# taken from edge rails / rails 2.0. Only needed on Rails 1.2.3
def assert_difference(expressions, difference = 1, message = nil, &block)
expression_evaluations = [expressions].flatten.collect{|expression| lambda { eval(expression, block.binding) } }
original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression.call }
yield
expression_evaluations.each_with_index do |expression, i|
assert_equal original_values[i] + difference, expression.call, message
end
end
# taken from edge rails / rails 2.0. Only needed on Rails 1.2.3
def assert_no_difference(expressions, message = nil, &block)
assert_difference expressions, 0, message, &block
end
end

View File

@ -0,0 +1,31 @@
# This controller handles the login/logout function of the site.
class <%= controller_class_name %>Controller < ApplicationController
# Be sure to include AuthenticationSystem in Application Controller instead
include AuthenticatedSystem
# render new.rhtml
def new
end
def create
self.current_<%= file_name %> = <%= class_name %>.authenticate(params[:login], params[:password])
if logged_in?
if params[:remember_me] == "1"
self.current_<%= file_name %>.remember_me
cookies[:auth_token] = { :value => self.current_<%= file_name %>.remember_token , :expires => self.current_<%= file_name %>.remember_token_expires_at }
end
redirect_back_or_default('/')
flash[:notice] = "Logged in successfully"
else
render :action => 'new'
end
end
def destroy
self.current_<%= file_name %>.forget_me if logged_in?
cookies.delete :auth_token
reset_session
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end
end

View File

@ -0,0 +1,17 @@
quentin:
id: 1
login: quentin
email: quentin@example.com
salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd
crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test
created_at: <%%= 5.days.ago.to_s :db %>
<% if options[:include_activation] %> activation_code: 8f24789ae988411ccf33ab0c30fe9106fab32e9b <% end %>
<% if options[:include_activation] %> activated_at: <%%= 5.days.ago.to_s :db %> <% end %>
aaron:
id: 2
login: aaron
email: aaron@example.com
salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd
crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test
created_at: <%%= 1.days.ago.to_s :db %>
<% if options[:include_activation] %> activation_code: 8f24789ae988411ccf33ab0c30fe9106fab32e9a <% end %>

View File

@ -0,0 +1,85 @@
require File.dirname(__FILE__) + '/../test_helper'
require '<%= controller_file_name %>_controller'
# Re-raise errors caught by the controller.
class <%= controller_class_name %>Controller; def rescue_action(e) raise e end; end
class <%= controller_class_name %>ControllerTest < Test::Unit::TestCase
# Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead
# Then, you can remove it from this and the units test.
include AuthenticatedTestHelper
fixtures :<%= table_name %>
def setup
@controller = <%= controller_class_name %>Controller.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_should_login_and_redirect
post :create, :login => 'quentin', :password => 'test'
assert session[:<%= file_name %>]
assert_response :redirect
end
def test_should_fail_login_and_not_redirect
post :create, :login => 'quentin', :password => 'bad password'
assert_nil session[:<%= file_name %>]
assert_response :success
end
def test_should_logout
login_as :quentin
get :destroy
assert_nil session[:<%= file_name %>]
assert_response :redirect
end
def test_should_remember_me
post :create, :login => 'quentin', :password => 'test', :remember_me => "1"
assert_not_nil @response.cookies["auth_token"]
end
def test_should_not_remember_me
post :create, :login => 'quentin', :password => 'test', :remember_me => "0"
assert_nil @response.cookies["auth_token"]
end
def test_should_delete_token_on_logout
login_as :quentin
get :destroy
assert_equal @response.cookies["auth_token"], []
end
def test_should_login_with_cookie
<%= table_name %>(:quentin).remember_me
@request.cookies["auth_token"] = cookie_for(:quentin)
get :new
assert @controller.send(:logged_in?)
end
def test_should_fail_expired_cookie_login
<%= table_name %>(:quentin).remember_me
<%= table_name %>(:quentin).update_attribute :remember_token_expires_at, 5.minutes.ago
@request.cookies["auth_token"] = cookie_for(:quentin)
get :new
assert !@controller.send(:logged_in?)
end
def test_should_fail_cookie_login
<%= table_name %>(:quentin).remember_me
@request.cookies["auth_token"] = auth_token('invalid_auth_token')
get :new
assert !@controller.send(:logged_in?)
end
protected
def auth_token(token)
CGI::Cookie.new('name' => 'auth_token', 'value' => token)
end
def cookie_for(<%= file_name %>)
auth_token <%= table_name %>(<%= file_name %>).remember_token
end
end

View File

@ -0,0 +1,2 @@
module <%= controller_class_name %>Helper
end

View File

@ -0,0 +1,14 @@
<%% form_tag <%= controller_singular_name.singularize %>_path do -%>
<p><label for="login">Login</label><br/>
<%%= text_field_tag 'login' %></p>
<p><label for="password">Password</label><br/>
<%%= password_field_tag 'password' %></p>
<!-- Uncomment this if you want this functionality
<p><label for="remember_me">Remember me:</label>
<%%= check_box_tag 'remember_me' %></p>
-->
<p><%%= submit_tag 'Log in' %></p>
<%% end -%>

View File

@ -0,0 +1,25 @@
class <%= class_name %>Mailer < ActionMailer::Base
def signup_notification(<%= file_name %>)
setup_email(<%= file_name %>)
@subject += 'Please activate your new account'
<% if options[:include_activation] %>
@body[:url] = "http://YOURSITE/activate/#{<%= file_name %>.activation_code}"
<% else %>
@body[:url] = "http://YOURSITE/login/" <% end %>
end
def activation(<%= file_name %>)
setup_email(<%= file_name %>)
@subject += 'Your account has been activated!'
@body[:url] = "http://YOURSITE/"
end
protected
def setup_email(<%= file_name %>)
@recipients = "#{<%= file_name %>.email}"
@from = "ADMINEMAIL"
@subject = "[YOURSITE] "
@sent_on = Time.now
@body[:<%= file_name %>] = <%= file_name %>
end
end

View File

@ -0,0 +1,31 @@
require File.dirname(__FILE__) + '/../test_helper'
require '<%= file_name %>_mailer'
class <%= class_name %>MailerTest < Test::Unit::TestCase
FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures'
CHARSET = "utf-8"
include ActionMailer::Quoting
def setup
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@expected = TMail::Mail.new
@expected.set_content_type "text", "plain", { "charset" => CHARSET }
end
def test_dummy_test
#do nothing
end
private
def read_fixture(action)
IO.readlines("#{FIXTURES_PATH}/<%= file_name %>_mailer/#{action}")
end
def encode(subject)
quoted_printable(subject, CHARSET)
end
end

View File

@ -0,0 +1,21 @@
class <%= migration_name %> < ActiveRecord::Migration
def self.up
create_table "<%= table_name %>", :force => true do |t|
t.column :login, :string
t.column :email, :string
t.column :crypted_password, :string, :limit => 40
t.column :salt, :string, :limit => 40
t.column :created_at, :datetime
t.column :updated_at, :datetime
t.column :remember_token, :string
t.column :remember_token_expires_at, :datetime
<% if options[:include_activation] %>
t.column :activation_code, :string, :limit => 40
t.column :activated_at, :datetime<% end %>
end
end
def self.down
drop_table "<%= table_name %>"
end
end

View File

@ -0,0 +1,98 @@
require 'digest/sha1'
class <%= class_name %> < ActiveRecord::Base
# Virtual attribute for the unencrypted password
attr_accessor :password
validates_presence_of :login, :email
validates_presence_of :password, :if => :password_required?
validates_presence_of :password_confirmation, :if => :password_required?
validates_length_of :password, :within => 4..40, :if => :password_required?
validates_confirmation_of :password, :if => :password_required?
validates_length_of :login, :within => 3..40
validates_length_of :email, :within => 3..100
validates_uniqueness_of :login, :email, :case_sensitive => false
before_save :encrypt_password
<% if options[:include_activation] %>before_create :make_activation_code <% end %>
# prevents a user from submitting a crafted form that bypasses activation
# anything else you want your user to change should be added here.
attr_accessible :login, :email, :password, :password_confirmation
<% if options[:include_activation] %>
# Activates the user in the database.
def activate
@activated = true
self.activated_at = Time.now.utc
self.activation_code = nil
save(false)
end
def activated?
# the existence of an activation code means they have not activated yet
activation_code.nil?
end
# Returns true if the user has just been activated.
def recently_activated?
@activated
end
<% end %>
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
def self.authenticate(login, password)
u = <% if options[:include_activation] %>find :first, :conditions => ['login = ? and activated_at IS NOT NULL', login]<% else %>find_by_login(login)<% end %> # need to get the salt
u && u.authenticated?(password) ? u : nil
end
# Encrypts some data with the salt.
def self.encrypt(password, salt)
Digest::SHA1.hexdigest("--#{salt}--#{password}--")
end
# Encrypts the password with the user salt
def encrypt(password)
self.class.encrypt(password, salt)
end
def authenticated?(password)
crypted_password == encrypt(password)
end
def remember_token?
remember_token_expires_at && Time.now.utc < remember_token_expires_at
end
# These create and unset the fields required for remembering users between browser closes
def remember_me
remember_me_for 2.weeks
end
def remember_me_for(time)
remember_me_until time.from_now.utc
end
def remember_me_until(time)
self.remember_token_expires_at = time
self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
save(false)
end
def forget_me
self.remember_token_expires_at = nil
self.remember_token = nil
save(false)
end
protected
# before filter
def encrypt_password
return if password.blank?
self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
self.crypted_password = encrypt(password)
end
def password_required?
crypted_password.blank? || !password.blank?
end
<% if options[:include_activation] %>
def make_activation_code
self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
end <% end %>
end

View File

@ -0,0 +1,30 @@
class <%= model_controller_class_name %>Controller < ApplicationController
# Be sure to include AuthenticationSystem in Application Controller instead
include AuthenticatedSystem
# render new.rhtml
def new
end
def create
cookies.delete :auth_token
reset_session
@<%= file_name %> = <%= class_name %>.new(params[:<%= file_name %>])
@<%= file_name %>.save!
self.current_<%= file_name %> = @<%= file_name %>
redirect_back_or_default('/')
flash[:notice] = "Thanks for signing up!"
rescue ActiveRecord::RecordInvalid
render :action => 'new'
end
<% if options[:include_activation] %>
def activate
self.current_<%= file_name %> = params[:activation_code].blank? ? :false : <%= class_name %>.find_by_activation_code(params[:activation_code])
if logged_in? && !current_<%= file_name %>.activated?
current_<%= file_name %>.activate
flash[:notice] = "Signup complete!"
end
redirect_back_or_default('/')
end
<% end %>
end

View File

@ -0,0 +1,86 @@
require File.dirname(__FILE__) + '/../test_helper'
require '<%= model_controller_file_name %>_controller'
# Re-raise errors caught by the controller.
class <%= model_controller_class_name %>Controller; def rescue_action(e) raise e end; end
class <%= model_controller_class_name %>ControllerTest < Test::Unit::TestCase
# Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead
# Then, you can remove it from this and the units test.
include AuthenticatedTestHelper
fixtures :<%= table_name %>
def setup
@controller = <%= model_controller_class_name %>Controller.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_should_allow_signup
assert_difference '<%= class_name %>.count' do
create_<%= file_name %>
assert_response :redirect
end
end
def test_should_require_login_on_signup
assert_no_difference '<%= class_name %>.count' do
create_<%= file_name %>(:login => nil)
assert assigns(:<%= file_name %>).errors.on(:login)
assert_response :success
end
end
def test_should_require_password_on_signup
assert_no_difference '<%= class_name %>.count' do
create_<%= file_name %>(:password => nil)
assert assigns(:<%= file_name %>).errors.on(:password)
assert_response :success
end
end
def test_should_require_password_confirmation_on_signup
assert_no_difference '<%= class_name %>.count' do
create_<%= file_name %>(:password_confirmation => nil)
assert assigns(:<%= file_name %>).errors.on(:password_confirmation)
assert_response :success
end
end
def test_should_require_email_on_signup
assert_no_difference '<%= class_name %>.count' do
create_<%= file_name %>(:email => nil)
assert assigns(:<%= file_name %>).errors.on(:email)
assert_response :success
end
end
<% if options[:include_activation] %>
def test_should_activate_user
assert_nil <%= class_name %>.authenticate('aaron', 'test')
get :activate, :activation_code => <%= table_name %>(:aaron).activation_code
assert_redirected_to '/'
assert_not_nil flash[:notice]
assert_equal <%= table_name %>(:aaron), <%= class_name %>.authenticate('aaron', 'test')
end
def test_should_not_activate_user_without_key
get :activate
assert_nil flash[:notice]
rescue ActionController::RoutingError
# in the event your routes deny this, we'll just bow out gracefully.
end
def test_should_not_activate_user_with_blank_key
get :activate, :activation_code => ''
assert_nil flash[:notice]
rescue ActionController::RoutingError
# well played, sir
end<% end %>
protected
def create_<%= file_name %>(options = {})
post :create, :<%= file_name %> => { :login => 'quire', :email => 'quire@example.com',
:password => 'quire', :password_confirmation => 'quire' }.merge(options)
end
end

View File

@ -0,0 +1,2 @@
module <%= model_controller_class_name %>Helper
end

View File

@ -0,0 +1,11 @@
class <%= class_name %>Observer < ActiveRecord::Observer
def after_create(<%= file_name %>)
<%= class_name %>Mailer.deliver_signup_notification(<%= file_name %>)
end
def after_save(<%= file_name %>)
<% if options[:include_activation] %>
<%= class_name %>Mailer.deliver_activation(<%= file_name %>) if <%= file_name %>.recently_activated?
<% end %>
end
end

View File

@ -0,0 +1,16 @@
<%%= error_messages_for :<%= file_name %> %>
<%% form_for :<%= file_name %>, :url => <%= table_name %>_path do |f| -%>
<p><label for="login">Login</label><br/>
<%%= f.text_field :login %></p>
<p><label for="email">Email</label><br/>
<%%= f.text_field :email %></p>
<p><label for="password">Password</label><br/>
<%%= f.password_field :password %></p>
<p><label for="password_confirmation">Confirm Password</label><br/>
<%%= f.password_field :password_confirmation %></p>
<p><%%= submit_tag 'Sign up' %></p>
<%% end -%>

View File

@ -0,0 +1,8 @@
Your account has been created.
Username: <%%= @<%= file_name %>.login %>
Password: <%%= @<%= file_name %>.password %>
Visit this url to activate your account:
<%%= @url %>

View File

@ -0,0 +1,101 @@
require File.dirname(__FILE__) + '/../test_helper'
class <%= class_name %>Test < Test::Unit::TestCase
# Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead.
# Then, you can remove it from this and the functional test.
include AuthenticatedTestHelper
fixtures :<%= table_name %>
def test_should_create_<%= file_name %>
assert_difference '<%= class_name %>.count' do
<%= file_name %> = create_<%= file_name %>
assert !<%= file_name %>.new_record?, "#{<%= file_name %>.errors.full_messages.to_sentence}"
end
end
def test_should_require_login
assert_no_difference '<%= class_name %>.count' do
u = create_<%= file_name %>(:login => nil)
assert u.errors.on(:login)
end
end
def test_should_require_password
assert_no_difference '<%= class_name %>.count' do
u = create_<%= file_name %>(:password => nil)
assert u.errors.on(:password)
end
end
def test_should_require_password_confirmation
assert_no_difference '<%= class_name %>.count' do
u = create_<%= file_name %>(:password_confirmation => nil)
assert u.errors.on(:password_confirmation)
end
end
def test_should_require_email
assert_no_difference '<%= class_name %>.count' do
u = create_<%= file_name %>(:email => nil)
assert u.errors.on(:email)
end
end
def test_should_reset_password
<%= table_name %>(:quentin).update_attributes(:password => 'new password', :password_confirmation => 'new password')
assert_equal <%= table_name %>(:quentin), <%= class_name %>.authenticate('quentin', 'new password')
end
def test_should_not_rehash_password
<%= table_name %>(:quentin).update_attributes(:login => 'quentin2')
assert_equal <%= table_name %>(:quentin), <%= class_name %>.authenticate('quentin2', 'test')
end
def test_should_authenticate_<%= file_name %>
assert_equal <%= table_name %>(:quentin), <%= class_name %>.authenticate('quentin', 'test')
end
def test_should_set_remember_token
<%= table_name %>(:quentin).remember_me
assert_not_nil <%= table_name %>(:quentin).remember_token
assert_not_nil <%= table_name %>(:quentin).remember_token_expires_at
end
def test_should_unset_remember_token
<%= table_name %>(:quentin).remember_me
assert_not_nil <%= table_name %>(:quentin).remember_token
<%= table_name %>(:quentin).forget_me
assert_nil <%= table_name %>(:quentin).remember_token
end
def test_should_remember_me_for_one_week
before = 1.week.from_now.utc
<%= table_name %>(:quentin).remember_me_for 1.week
after = 1.week.from_now.utc
assert_not_nil <%= table_name %>(:quentin).remember_token
assert_not_nil <%= table_name %>(:quentin).remember_token_expires_at
assert <%= table_name %>(:quentin).remember_token_expires_at.between?(before, after)
end
def test_should_remember_me_until_one_week
time = 1.week.from_now.utc
<%= table_name %>(:quentin).remember_me_until time
assert_not_nil <%= table_name %>(:quentin).remember_token
assert_not_nil <%= table_name %>(:quentin).remember_token_expires_at
assert_equal <%= table_name %>(:quentin).remember_token_expires_at, time
end
def test_should_remember_me_default_two_weeks
before = 2.weeks.from_now.utc
<%= table_name %>(:quentin).remember_me
after = 2.weeks.from_now.utc
assert_not_nil <%= table_name %>(:quentin).remember_token
assert_not_nil <%= table_name %>(:quentin).remember_token_expires_at
assert <%= table_name %>(:quentin).remember_token_expires_at.between?(before, after)
end
protected
def create_<%= file_name %>(options = {})
<%= class_name %>.create({ :login => 'quire', :email => 'quire@example.com', :password => 'quire', :password_confirmation => 'quire' }.merge(options))
end
end

View File

@ -0,0 +1 @@
puts IO.read(File.join(File.dirname(__FILE__), 'README'))

View File

@ -0,0 +1,18 @@
Copyright (c) 2007 PJ Hyett and Mislav Marohnić
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.

View File

@ -0,0 +1,119 @@
= WillPaginate
Pagination is just limiting the number of records displayed. Why should you let
it get in your way while doing more important tasks on your project? This
plugin makes magic happen. Ever wanted to be able to do just this:
Post.paginate :page => 1
... and then render the page links with a single call to a view helper? Well,
now you can. Simply:
script/plugin install svn://errtheblog.com/svn/plugins/will_paginate
Ryan Bates made an awesome screencast[http://railscasts.com/episodes/51], check
it out.
== Example usage:
Use a paginate finder in the controller:
@posts = Post.paginate_by_board_id @board.id, :page => params[:page]
Yeah, +paginate+ works just like +find+ -- it just doesn't fetch all the
records. Don't forget to tell it which page you want, or it will complain!
Read more on WillPaginate::Finder::ClassMethods.
Render the posts in your view like you would normally do. When you need to render
pagination, just stick this in:
<%= will_paginate @posts %>
You're done. (Copy and paste the example fancy CSS styles from the bottom.) You
can find the option list at WillPaginate::ViewHelpers.
How does it know how much items to fetch per page? It asks your model by calling
+Post.per_page+. You can define it like this:
class Post < ActiveRecord::Base
cattr_reader :per_page
@@per_page = 50
end
... or like this:
class Post < ActiveRecord::Base
def self.per_page
50
end
end
... or don't worry about it at all. (WillPaginate defines it to be 30 if missing.)
You can also specify the count explicitly when calling +paginate+:
@posts = Post.paginate :page => params[:page], :per_page => 50
The +paginate+ finder wraps the original finder and returns your resultset that now has
some new properties. You can use the collection as you would with any ActiveRecord
resultset, but WillPaginate view helpers also need that object to be able to render pagination:
<ol>
<% for post in @posts -%>
<li>Render `post` in some nice way.</li>
<% end -%>
</ol>
<p>Now let's render us some pagination!</p>
<%= will_paginate @posts %>
== Authors, credits, contact!
REPORT BUGS on Lighthouse: http://err.lighthouseapp.com/projects/466-plugins/overview
BROWSE SOURCE on Warehouse: http://plugins.require.errtheblog.com/browser/will_paginate
Want to discuss, request features, ask questions? Join the Google group:
http://groups.google.com/group/will_paginate
Ruby port by: PJ Hyett, Mislav Marohnić (Sulien)
Original announcement: http://errtheblog.com/post/929
Original PHP source: http://www.strangerstudios.com/sandbox/pagination/diggstyle.php
Contributors: Chris Wanstrath, Dr. Nic Williams, K. Adam Christensen,
Mike Garey, Bence Golda, Matt Aimonetti, Charles Brian Quinn,
Desi McAdam, James Coglan, Matijs van Zuijlen
== Want Digg style?
Copy the following css into your stylesheet for a good start:
.pagination {
padding: 3px;
margin: 3px;
}
.pagination a {
padding: 2px 5px 2px 5px;
margin: 2px;
border: 1px solid #aaaadd;
text-decoration: none;
color: #000099;
}
.pagination a:hover, .pagination a:active {
border: 1px solid #000099;
color: #000;
}
.pagination span.current {
padding: 2px 5px 2px 5px;
margin: 2px;
border: 1px solid #000099;
font-weight: bold;
background-color: #000099;
color: #FFF;
}
.pagination span.disabled {
padding: 2px 5px 2px 5px;
margin: 2px;
border: 1px solid #eee;
color: #ddd;
}

View File

@ -0,0 +1,26 @@
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
desc 'Default: run unit tests.'
task :default => :test
desc 'Test the will_paginate plugin.'
Rake::TestTask.new(:test) do |t|
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end
desc 'Generate RDoc documentation for the will_paginate plugin.'
Rake::RDocTask.new(:rdoc) do |rdoc|
files = ['README', 'LICENSE', 'lib/**/*.rb']
rdoc.rdoc_files.add(files)
rdoc.main = "README" # page to start on
rdoc.title = "will_paginate"
templates = %w[/Users/chris/ruby/projects/err/rock/template.rb /var/www/rock/template.rb]
rdoc.template = templates.find { |t| File.exists? t }
rdoc.rdoc_dir = 'doc' # rdoc output folder
rdoc.options << '--inline-source'
end

View File

@ -0,0 +1,4 @@
unless ActiveRecord::Base.respond_to? :paginate
require 'will_paginate'
WillPaginate.enable
end

View File

@ -0,0 +1,57 @@
require 'active_support'
# = You *will* paginate!
#
# First read about WillPaginate::Finder::ClassMethods, then see
# WillPaginate::ViewHelpers. The magical array you're handling in-between is
# WillPaginate::Collection.
#
# Happy paginating!
module WillPaginate
class << self
def enable
enable_actionpack
enable_activerecord
end
def enable_actionpack
return if ActionView::Base.instance_methods.include? 'will_paginate'
require 'will_paginate/view_helpers'
ActionView::Base.class_eval { include ViewHelpers }
end
def enable_activerecord
return if ActiveRecord::Base.respond_to? :paginate
require 'will_paginate/finder'
ActiveRecord::Base.class_eval { include Finder }
associations = ActiveRecord::Associations
collection = associations::AssociationCollection
# to support paginating finders on associations, we have to mix in the
# method_missing magic from WillPaginate::Finder::ClassMethods to AssociationProxy
# subclasses, but in a different way for Rails 1.2.x and 2.0
(collection.instance_methods.include?(:create!) ?
collection : collection.subclasses.map(&:constantize)
).push(associations::HasManyThroughAssociation).each do |klass|
klass.class_eval do
include Finder::ClassMethods
alias_method_chain :method_missing, :paginate
end
end
end
end
module Deprecation
extend ActiveSupport::Deprecation
def self.warn(message, callstack = caller)
message = 'WillPaginate: ' + message.strip.gsub(/ {3,}/, ' ')
behavior.call(message, callstack) if behavior && !silenced?
end
def self.silenced?
ActiveSupport::Deprecation.silenced?
end
end
end

View File

@ -0,0 +1,113 @@
module WillPaginate
# Arrays returned from paginating finds are, in fact, instances of this.
# You may think of WillPaginate::Collection as an ordinary array with some
# extra properties. Those properties are used by view helpers to generate
# correct page links.
#
# WillPaginate::Collection also assists in rolling out your own pagination
# solutions: see +create+.
#
class Collection < Array
attr_reader :current_page, :per_page, :total_entries
# Arguments to this constructor are the current page number, per-page limit
# and the total number of entries. The last argument is optional because it
# is best to do lazy counting; in other words, count *conditionally* after
# populating the collection using the +replace+ method.
#
def initialize(page, per_page, total = nil)
@current_page = page.to_i
@per_page = per_page.to_i
self.total_entries = total if total
end
# Just like +new+, but yields the object after instantiation and returns it
# afterwards. This is very useful for manual pagination:
#
# @entries = WillPaginate::Collection.create(1, 10) do |pager|
# result = Post.find(:all, :limit => pager.per_page, :offset => pager.offset)
# # inject the result array into the paginated collection:
# pager.replace(result)
#
# unless pager.total_entries
# # the pager didn't manage to guess the total count, do it manually
# pager.total_entries = Post.count
# end
# end
#
# The possibilities with this are endless. For another example, here is how
# WillPaginate defines pagination on Array instances:
#
# Array.class_eval do
# def paginate(page = 1, per_page = 15)
# WillPaginate::Collection.create(page, per_page, size) do |pager|
# pager.replace self[pager.offset, pager.per_page].to_a
# end
# end
# end
#
def self.create(page, per_page, total = nil, &block)
pager = new(page, per_page, total)
yield pager
pager
end
# The total number of pages.
def page_count
@total_pages
end
# Helper method that is true when someone tries to fetch a page with a larger
# number than the last page or with a number smaller than 1
def out_of_bounds?
current_page > page_count or current_page < 1
end
# Current offset of the paginated collection. If we're on the first page,
# it is always 0. If we're on the 2nd page and there are 30 entries per page,
# the offset is 30. This property is useful if you want to render ordinals
# besides your records: simply start with offset + 1.
#
def offset
(current_page - 1) * per_page
end
# current_page - 1 or nil if there is no previous page
def previous_page
current_page > 1 ? (current_page - 1) : nil
end
# current_page + 1 or nil if there is no next page
def next_page
current_page < page_count ? (current_page + 1) : nil
end
def total_entries=(number)
@total_entries = number.to_i
@total_pages = (@total_entries / per_page.to_f).ceil
end
# This is a magic wrapper for the original Array#replace method. It serves
# for populating the paginated collection after initialization.
#
# Why magic? Because it tries to guess the total number of entries judging
# by the size of given array. If it is shorter than +per_page+ limit, then we
# know we're on the last page. This trick is very useful for avoiding
# unnecessary hits to the database to do the counting after we fetched the
# data for the current page.
#
# However, after using +replace+ you should always test the value of
# +total_entries+ and set it to a proper value if it's +nil+. See the example
# in +create+.
def replace(array)
returning super do
# The collection is shorter then page limit? Rejoice, because
# then we know that we are on the last page!
if total_entries.nil? and length > 0 and length < per_page
self.total_entries = offset + length
end
end
end
end
end

View File

@ -0,0 +1,61 @@
require 'set'
unless Hash.instance_methods.include? 'except'
Hash.class_eval do
# Returns a new hash without the given keys.
def except(*keys)
rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
reject { |key,| rejected.include?(key) }
end
# Replaces the hash without only the given keys.
def except!(*keys)
replace(except(*keys))
end
end
end
unless Hash.instance_methods.include? 'slice'
Hash.class_eval do
# Returns a new hash with only the given keys.
def slice(*keys)
allowed = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
reject { |key,| !allowed.include?(key) }
end
# Replaces the hash with only the given keys.
def slice!(*keys)
replace(slice(*keys))
end
end
end
require 'will_paginate/collection'
unless Array.instance_methods.include? 'paginate'
# http://www.desimcadam.com/archives/8
Array.class_eval do
def paginate(options_or_page = {}, per_page = nil)
if options_or_page.nil? or Fixnum === options_or_page
if defined? WillPaginate::Deprecation
WillPaginate::Deprecation.warn <<-DEPR
Array#paginate now conforms to the main, ActiveRecord::Base#paginate API. You should \
call it with a parameters hash (:page, :per_page). The old API (numbers as arguments) \
has been deprecated and is going to be unsupported in future versions of will_paginate.
DEPR
end
page = options_or_page
options = {}
else
options = options_or_page
page = options[:page] || 1
raise ArgumentError, "wrong number of arguments (1 hash or 2 Fixnums expected)" if per_page
per_page = options[:per_page]
end
WillPaginate::Collection.create(page || 1, per_page || 30, options[:total_entries] || size) do |pager|
pager.replace self[pager.offset, pager.per_page].to_a
end
end
end
end

View File

@ -0,0 +1,174 @@
require 'will_paginate/core_ext'
module WillPaginate
# A mixin for ActiveRecord::Base. Provides +per_page+ class method
# and makes +paginate+ finders possible with some method_missing magic.
#
# Find out more in WillPaginate::Finder::ClassMethods
#
module Finder
def self.included(base)
base.extend ClassMethods
class << base
alias_method_chain :method_missing, :paginate
define_method(:per_page) { 30 } unless respond_to?(:per_page)
end
end
# = Paginating finders for ActiveRecord models
#
# WillPaginate doesn't really add extra methods to your ActiveRecord models (except +per_page+
# unless it's already available). It simply intercepts
# the calls to paginating finders such as +paginate+, +paginate_by_user_id+ (and so on) and
# translates them to ordinary finders: +find+, +find_by_user_id+, etc. It does so with some
# method_missing magic, but you don't need to care for that. You simply use paginating finders
# same way you used ordinary ones. You only need to tell them what page you want in options.
#
# @topics = Topic.paginate :all, :page => params[:page]
#
# In paginating finders, "all" is implicit. No sense in paginating a single record, right? So:
#
# Post.paginate => Post.find :all
# Post.paginate_all_by_something => Post.find_all_by_something
# Post.paginate_by_something => Post.find_all_by_something
#
# Knowing that, the above example can be written simply as:
#
# @topics = Topic.paginate :page => params[:page]
#
# Don't forget to pass the +page+ parameter! Without it, paginating finders will raise an error.
#
# == Options
# Options for paginating finders are:
#
# page REQUIRED, but defaults to 1 if false or nil
# per_page (default is read from the model, which is 30 if not overridden)
# total entries not needed unless you want to count the records yourself somehow
# count hash of options that are used only for the call to count
#
module ClassMethods
# This methods wraps +find_by_sql+ by simply adding LIMIT and OFFSET to your SQL string
# based on the params otherwise used by paginating finds: +page+ and +per_page+.
#
# Example:
#
# @developers = Developer.paginate_by_sql ['select * from developers where salary > ?', 80000],
# :page => params[:page], :per_page => 3
#
def paginate_by_sql(sql, options)
options, page, per_page = wp_parse_options!(options)
WillPaginate::Collection.create(page, per_page) do |pager|
query = sanitize_sql(sql)
count_query = "SELECT COUNT(*) FROM (#{query}) AS count_table" unless options[:total_entries]
options.update :offset => pager.offset, :limit => pager.per_page
add_limit! query, options
pager.replace find_by_sql(query)
pager.total_entries = options[:total_entries] || count_by_sql(count_query) unless pager.total_entries
end
end
def respond_to?(method, include_priv = false)
case method.to_sym
when :paginate, :paginate_by_sql
true
else
super(method.to_s.sub(/^paginate/, 'find'), include_priv)
end
end
protected
def method_missing_with_paginate(method, *args, &block)
# did somebody tried to paginate? if not, let them be
unless method.to_s.index('paginate') == 0
return method_missing_without_paginate(method, *args, &block)
end
options, page, per_page, total_entries = wp_parse_options!(args.pop)
# an array of IDs may have been given:
total_entries ||= (Array === args.first and args.first.size)
# paginate finders are really just find_* with limit and offset
finder = method.to_s.sub /^paginate/, 'find'
# :all is implicit
if finder == 'find'
args.unshift(:all) if args.empty?
elsif finder.index('find_by_') == 0
finder.sub! /^find/, 'find_all'
end
WillPaginate::Collection.create(page, per_page, total_entries) do |pager|
args << options.except(:count).merge(:offset => pager.offset, :limit => pager.per_page)
pager.replace send(finder, *args)
# magic counting for user convenience:
pager.total_entries = wp_count!(options, args, finder) unless pager.total_entries
end
end
def wp_count!(options, args, finder)
excludees = [:count, :order, :limit, :offset]
unless options[:select] and options[:select] =~ /^\s*DISTINCT/i
excludees << :select # only exclude the select param if it doesn't begin with DISTINCT
end
# count expects (almost) the same options as find
count_options = options.except *excludees
# merge the hash found in :count
# this allows you to specify :select, :order, or anything else just for the count query
count_options.update(options.delete(:count) || {}) if options.key? :count
# we may have to scope ...
counter = Proc.new { count(count_options) }
# we may be in a model or an association proxy!
klass = (@owner and @reflection) ? @reflection.klass : self
count = if finder =~ /^find_/ and klass.respond_to?(scoper = finder.sub(/^find_/, 'with_'))
# scope_out adds a 'with_finder' method which acts like with_scope, if it's present
# then execute the count with the scoping provided by the with_finder
send(scoper, &counter)
elsif conditions = wp_extract_finder_conditions(finder, args)
# extracted the conditions from calls like "paginate_by_foo_and_bar"
with_scope(:find => { :conditions => conditions }, &counter)
else
counter.call
end
count.respond_to?(:length) ? count.length : count
end
def wp_parse_options!(options)
raise ArgumentError, 'hash parameters expected' unless options.respond_to? :symbolize_keys!
options.symbolize_keys!
raise ArgumentError, ':page parameter required' unless options.key? :page
if options[:count] and options[:total_entries]
raise ArgumentError, ':count and :total_entries are mutually exclusive parameters'
end
page = options.delete(:page) || 1
per_page = options.delete(:per_page) || self.per_page
total = options.delete(:total_entries)
[options, page, per_page, total]
end
private
# thanks to active record for making us duplicate this code
def wp_extract_finder_conditions(finder, arguments)
return unless match = /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(finder.to_s)
attribute_names = extract_attribute_names_from_match(match)
unless all_attributes_exists?(attribute_names)
raise "I can't make sense of `#{finder}`. Try doing the count manually"
end
construct_attributes_from_arguments(attribute_names, arguments)
end
end
end
end

View File

@ -0,0 +1,136 @@
require 'will_paginate/core_ext'
module WillPaginate
# = Global options for pagination helpers
#
# Options for pagination helpers are optional and get their default values from the
# WillPaginate::ViewHelpers.pagination_options hash. You can write to this hash to
# override default options on the global level:
#
# WillPaginate::ViewHelpers.pagination_options[:prev_label] = 'Previous page'
#
# By putting this into your environment.rb you can easily translate link texts to previous
# and next pages, as well as override some other defaults to your liking.
module ViewHelpers
# default options that can be overridden on the global level
@@pagination_options = { :class => 'pagination',
:prev_label => '&laquo; Previous',
:next_label => 'Next &raquo;',
:inner_window => 4, # links around the current page
:outer_window => 1, # links around beginning and end
:separator => ' ', # single space is friendly to spiders and non-graphic browsers
:param_name => :page
}
mattr_reader :pagination_options
# Renders Digg-style pagination. (We know you wanna!)
# Returns nil if there is only one page in total (can't paginate that).
#
# Options for will_paginate view helper:
#
# class: CSS class name for the generated DIV (default "pagination")
# prev_label: default '&laquo; Previous',
# next_label: default 'Next &raquo;',
# inner_window: how many links are shown around the current page, defaults to 4
# outer_window: how many links are around the first and the last page, defaults to 1
# separator: string separator for page HTML elements, default " " (single space)
# param_name: parameter name for page number in URLs, defaults to "page"
#
# All extra options are passed to the generated container DIV, so eventually
# they become its HTML attributes.
#
def will_paginate(entries = @entries, options = {})
total_pages =
if entries.page_count > 1
renderer = WillPaginate::LinkRenderer.new entries, options, self
links = renderer.items
content_tag :div, links, renderer.html_options
end
end
end
# This class does the heavy lifting of actually building the pagination
# links. It is used by +will_paginate+ helper internally, but avoid using it
# directly (for now) because its API is not set in stone yet.
class LinkRenderer
def initialize(collection, options, template)
@collection = collection
@options = options.symbolize_keys.reverse_merge WillPaginate::ViewHelpers.pagination_options
@template = template
end
def items
returning windowed_paginator do |links|
# next and previous buttons
links.unshift page_link_or_span(@collection.previous_page, 'disabled', @options[:prev_label])
links.push page_link_or_span(@collection.next_page, 'disabled', @options[:next_label])
end.join(@options[:separator])
end
def html_options
@options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class])
end
protected
def windowed_paginator
inner_window, outer_window = @options[:inner_window].to_i, @options[:outer_window].to_i
min = page - inner_window
max = page + inner_window
# adjust lower or upper limit if other is out of bounds
if max > total_pages then min -= max - total_pages
elsif min < 1 then max += 1 - min
end
current = min..max
beginning = 1..(1 + outer_window)
tail = (total_pages - outer_window)..total_pages
visible = [beginning, current, tail].map(&:to_a).flatten.sort.uniq
links, prev = [], 0
visible.each do |n|
next if n < 1
break if n > total_pages
unless n - prev > 1
prev = n
links << page_link_or_span((n != page ? n : nil), 'current', n)
else
# ellipsis represents the gap between windows
prev = n - 1
links << '...'
redo
end
end
links
end
def page_link_or_span(page, span_class, text)
unless page
@template.content_tag :span, text, :class => span_class
else
# page links should preserve GET/POST parameters
@template.link_to text, @template.params.merge(param => page != 1 ? page : nil)
end
end
private
def page
@collection.current_page
end
def total_pages
@collection.page_count
end
def param
@options[:param_name].to_sym
end
end
end

View File

@ -0,0 +1,121 @@
require File.dirname(__FILE__) + '/helper'
require 'will_paginate'
require 'will_paginate/core_ext'
class ArrayPaginationTest < Test::Unit::TestCase
def test_simple
collection = ('a'..'e').to_a
[{ :page => 1, :per_page => 3, :expected => %w( a b c ) },
{ :page => 2, :per_page => 3, :expected => %w( d e ) },
{ :page => 1, :per_page => 5, :expected => %w( a b c d e ) },
{ :page => 3, :per_page => 5, :expected => [] },
{ :page => -1, :per_page => 5, :expected => [] },
{ :page => 1, :per_page => -5, :expected => [] },
].
each do |conditions|
assert_equal conditions[:expected], collection.paginate(conditions.slice(:page, :per_page))
end
end
def test_defaults
result = (1..50).to_a.paginate
assert_equal 1, result.current_page
assert_equal 30, result.size
end
def test_deprecated_api
assert_deprecated 'paginate API' do
result = (1..50).to_a.paginate(2, 10)
assert_equal 2, result.current_page
assert_equal (11..20).to_a, result
assert_equal 50, result.total_entries
end
assert_deprecated { [].paginate nil }
end
def test_total_entries_has_precedence
result = %w(a b c).paginate :total_entries => 5
assert_equal 5, result.total_entries
end
def test_argument_error_with_params_and_another_argument
assert_raise ArgumentError do
[].paginate({}, 5)
end
end
def test_paginated_collection
entries = %w(a b c)
collection = create(2, 3, 10) do |pager|
assert_equal entries, pager.replace(entries)
end
assert_equal entries, collection
assert_respond_to_all collection, %w(page_count each offset size current_page per_page total_entries)
assert_kind_of Array, collection
assert_instance_of Array, collection.entries
assert_equal 3, collection.offset
assert_equal 4, collection.page_count
assert !collection.out_of_bounds?
end
def test_out_of_bounds
entries = create(2, 3, 2){}
assert entries.out_of_bounds?
entries = create(0, 3, 2){}
assert entries.out_of_bounds?
entries = create(1, 3, 2){}
assert !entries.out_of_bounds?
end
def test_guessing_total_count
entries = create do |pager|
# collection is shorter than limit
pager.replace array
end
assert_equal 8, entries.total_entries
entries = create(2, 5, 10) do |pager|
# collection is shorter than limit, but we have an explicit count
pager.replace array
end
assert_equal 10, entries.total_entries
entries = create do |pager|
# collection is the same as limit; we can't guess
pager.replace array(5)
end
assert_equal nil, entries.total_entries
entries = create do |pager|
# collection is empty; we can't guess
pager.replace array(0)
end
assert_equal nil, entries.total_entries
end
private
def create(page = 2, limit = 5, total = nil, &block)
WillPaginate::Collection.create(page, limit, total, &block)
end
def array(size = 3)
Array.new(size)
end
def collect_deprecations
old_behavior = WillPaginate::Deprecation.behavior
deprecations = []
WillPaginate::Deprecation.behavior = Proc.new do |message, callstack|
deprecations << message
end
result = yield
[result, deprecations]
ensure
WillPaginate::Deprecation.behavior = old_behavior
end
end

View File

@ -0,0 +1,24 @@
plugin_root = File.join(File.dirname(__FILE__), '..')
# first look for a symlink to a copy of the framework
if framework_root = ["#{plugin_root}/rails", "#{plugin_root}/../../rails"].find { |p| File.directory? p }
puts "found framework root: #{framework_root}"
# this allows for a plugin to be tested outside an app
$:.unshift "#{framework_root}/activesupport/lib", "#{framework_root}/activerecord/lib", "#{framework_root}/actionpack/lib"
else
# is the plugin installed in an application?
app_root = plugin_root + '/../../..'
if File.directory? app_root + '/config'
puts 'using config/boot.rb'
ENV['RAILS_ENV'] = 'test'
require File.expand_path(app_root + '/config/boot')
else
# simply use installed gems if available
puts 'using rubygems'
require 'rubygems'
gem 'actionpack'; gem 'activerecord'
end
end
$:.unshift "#{plugin_root}/lib"

View File

@ -0,0 +1,9 @@
#!/usr/bin/env ruby
irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
libs = []
dirname = File.dirname(__FILE__)
libs << 'irb/completion'
libs << File.join(dirname, 'lib', 'load_fixtures')
exec "#{irb}#{libs.map{ |l| " -r #{l}" }.join} --simple-prompt"

View File

@ -0,0 +1,285 @@
require File.dirname(__FILE__) + '/helper'
require File.dirname(__FILE__) + '/lib/activerecord_test_case'
require 'will_paginate'
WillPaginate.enable_activerecord
class FinderTest < ActiveRecordTestCase
fixtures :topics, :replies, :users, :projects, :developers_projects
def test_new_methods_presence
assert_respond_to_all Topic, %w(per_page paginate paginate_by_sql)
end
def test_simple_paginate
entries = Topic.paginate :page => nil
assert_equal 1, entries.current_page
assert_nil entries.previous_page
assert_nil entries.next_page
assert_equal 1, entries.page_count
assert_equal 4, entries.size
entries = Topic.paginate :page => 2
assert_equal 2, entries.current_page
assert_equal 1, entries.previous_page
assert_equal 1, entries.page_count
assert entries.empty?
end
def test_parameter_api
# :page parameter in options is required!
assert_raise(ArgumentError){ Topic.paginate }
assert_raise(ArgumentError){ Topic.paginate({}) }
# explicit :all should not break anything
assert_equal Topic.paginate(:page => nil), Topic.paginate(:all, :page => 1)
# :count could be nil and we should still not cry
assert_nothing_raised { Topic.paginate :page => 1, :count => nil }
end
def test_paginate_with_per_page
entries = Topic.paginate :page => 1, :per_page => 1
assert_equal 1, entries.size
assert_equal 4, entries.page_count
# Developer class has explicit per_page at 10
entries = Developer.paginate :page => 1
assert_equal 10, entries.size
assert_equal 2, entries.page_count
entries = Developer.paginate :page => 1, :per_page => 5
assert_equal 11, entries.total_entries
assert_equal 5, entries.size
assert_equal 3, entries.page_count
end
def test_paginate_with_order
entries = Topic.paginate :page => 1, :order => 'created_at desc'
expected = [topics(:futurama), topics(:harvey_birdman), topics(:rails), topics(:ar)].reverse
assert_equal expected, entries.to_a
assert_equal 1, entries.page_count
end
def test_paginate_with_conditions
entries = Topic.paginate :page => 1, :conditions => ["created_at > ?", 30.minutes.ago]
expected = [topics(:rails), topics(:ar)]
assert_equal expected, entries.to_a
assert_equal 1, entries.page_count
end
def test_paginate_with_include_and_conditions
entries = Topic.paginate \
:page => 1,
:include => :replies,
:conditions => "replies.content LIKE 'Bird%' ",
:per_page => 10
expected = Topic.find :all,
:include => 'replies',
:conditions => "replies.content LIKE 'Bird%' ",
:limit => 10
assert_equal expected, entries.to_a
assert_equal 1, entries.total_entries
end
def test_paginate_with_include_and_order
entries = Topic.paginate \
:page => 1,
:include => :replies,
:order => 'replies.created_at asc, topics.created_at asc',
:per_page => 10
expected = Topic.find :all,
:include => 'replies',
:order => 'replies.created_at asc, topics.created_at asc',
:limit => 10
assert_equal expected, entries.to_a
assert_equal 4, entries.total_entries
end
def test_paginate_associations_with_include
entries, project = nil, projects(:active_record)
assert_nothing_raised "THIS IS A BUG in Rails 1.2.3 that was fixed in [7326]. " +
"Please upgrade to the 1-2-stable branch or edge Rails." do
entries = project.topics.paginate \
:page => 1,
:include => :replies,
:conditions => "replies.content LIKE 'Nice%' ",
:per_page => 10
end
expected = Topic.find :all,
:include => 'replies',
:conditions => "project_id = #{project.id} AND replies.content LIKE 'Nice%' ",
:limit => 10
assert_equal expected, entries.to_a
end
def test_paginate_associations
dhh = users :david
expected_name_ordered = [projects(:action_controller), projects(:active_record)]
expected_id_ordered = [projects(:active_record), projects(:action_controller)]
# with association-specified order
entries = dhh.projects.paginate(:page => 1)
assert_equal expected_name_ordered, entries
assert_equal 2, entries.total_entries
# with explicit order
entries = dhh.projects.paginate(:page => 1, :order => 'projects.id')
assert_equal expected_id_ordered, entries
assert_equal 2, entries.total_entries
assert_nothing_raised { dhh.projects.find(:all, :order => 'projects.id', :limit => 4) }
entries = dhh.projects.paginate(:page => 1, :order => 'projects.id', :per_page => 4)
assert_equal expected_id_ordered, entries
# has_many with implicit order
topic = Topic.find(1)
expected = [replies(:spam), replies(:witty_retort)]
assert_equal expected.map(&:id).sort, topic.replies.paginate(:page => 1).map(&:id).sort
assert_equal expected.reverse, topic.replies.paginate(:page => 1, :order => 'replies.id ASC')
end
def test_paginate_association_extension
project = Project.find(:first)
entries = project.replies.paginate_recent :page => 1
assert_equal [replies(:brave)], entries
end
def test_paginate_with_joins
entries = Developer.paginate :page => 1,
:joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
:conditions => 'project_id = 1'
assert_equal 2, entries.size
developer_names = entries.map { |d| d.name }
assert developer_names.include?('David')
assert developer_names.include?('Jamis')
expected = entries.to_a
entries = Developer.paginate :page => 1,
:joins => 'LEFT JOIN developers_projects ON users.id = developers_projects.developer_id',
:conditions => 'project_id = 1', :count => { :select => "users.id" }
assert_equal expected, entries.to_a
end
def test_paginate_with_group
entries = Developer.paginate :page => 1, :per_page => 10, :group => 'salary'
expected = [ users(:david), users(:jamis), users(:dev_10), users(:poor_jamis) ].map(&:salary).sort
assert_equal expected, entries.map(&:salary).sort
end
def test_paginate_with_dynamic_finder
expected = [replies(:witty_retort), replies(:spam)]
assert_equal expected, Reply.paginate_by_topic_id(1, :page => 1)
entries = Developer.paginate :conditions => { :salary => 100000 }, :page => 1, :per_page => 5
assert_equal 8, entries.total_entries
assert_equal entries, Developer.paginate_by_salary(100000, :page => 1, :per_page => 5)
# dynamic finder + conditions
entries = Developer.paginate_by_salary(100000, :page => 1,
:conditions => ['id > ?', 6])
assert_equal 4, entries.total_entries
assert_equal (7..10).to_a, entries.map(&:id)
assert_raises NoMethodError do
Developer.paginate_by_inexistent_attribute 100000, :page => 1
end
end
def test_paginate_by_sql
assert_respond_to Developer, :paginate_by_sql
entries = Developer.paginate_by_sql ['select * from users where salary > ?', 80000],
:page => 2, :per_page => 3, :total_entries => 9
assert_equal (5..7).to_a, entries.map(&:id)
assert_equal 9, entries.total_entries
end
def test_count_by_sql
entries = Developer.paginate_by_sql ['select * from users where salary > ?', 60000],
:page => 2, :per_page => 3
assert_equal 12, entries.total_entries
end
def test_count_distinct
entries = Developer.paginate :select => 'DISTINCT salary', :page => 1, :per_page => 4
assert_equal 4, entries.size
assert_equal 4, entries.total_entries
end
def test_scoped_paginate
entries =
Developer.with_poor_ones do
Developer.paginate :page => 1
end
assert_equal 2, entries.size
assert_equal 2, entries.total_entries
end
# Are we on edge? Find out by testing find_all which was removed in [6998]
unless Developer.respond_to? :find_all
def test_paginate_array_of_ids
# AR finders also accept arrays of IDs
# (this was broken in Rails before [6912])
entries = Developer.paginate((1..8).to_a, :per_page => 3, :page => 2)
assert_equal (4..6).to_a, entries.map(&:id)
assert_equal 8, entries.total_entries
end
end
uses_mocha 'parameter' do
def test_implicit_all_with_dynamic_finders
Topic.expects(:find_all_by_foo).returns([])
Topic.expects(:wp_extract_finder_conditions)
Topic.expects(:count)
Topic.paginate_by_foo :page => 1
end
def test_guessing_the_total_count
Topic.expects(:find).returns(Array.new(2))
Topic.expects(:count).never
entries = Topic.paginate :page => 2, :per_page => 4
assert_equal 6, entries.total_entries
end
def test_extra_parameters_stay_untouched
Topic.expects(:find).with() { |*args| args.last.key? :foo }.returns(Array.new(5))
Topic.expects(:count).with(){ |*args| args.last.key? :foo }.returns(1)
Topic.paginate :foo => 'bar', :page => 1, :per_page => 4
end
def test_count_doesnt_use_select_options
Developer.expects(:find).with() { |*args| args.last.key? :select }.returns(Array.new(5))
Developer.expects(:count).with(){ |*args| !args.last.key?(:select) }.returns(1)
Developer.paginate :select => 'users.*', :page => 1, :per_page => 4
end
def test_should_use_scoped_finders_if_present
# scope-out compatibility
Topic.expects(:find_best).returns(Array.new(5))
Topic.expects(:with_best).returns(1)
Topic.paginate_best :page => 1, :per_page => 4
end
def test_ability_to_use_with_custom_finders
# acts_as_taggable defines `find_tagged_with(tag, options)`
Topic.expects(:find_tagged_with).with('will_paginate', :offset => 0, :limit => 5).returns([])
Topic.expects(:count).with({}).returns(0)
Topic.paginate_tagged_with 'will_paginate', :page => 1, :per_page => 5
end
end
end

View File

@ -0,0 +1,3 @@
class Admin < User
has_many :companies, :finder_sql => 'SELECT * FROM companies'
end

View File

@ -0,0 +1,11 @@
class Developer < User
has_and_belongs_to_many :projects, :include => :topics, :order => 'projects.name'
def self.with_poor_ones(&block)
with_scope :find => { :conditions => ['salary <= ?', 80000], :order => 'salary' } do
yield
end
end
def self.per_page() 10 end
end

View File

@ -0,0 +1,13 @@
david_action_controller:
developer_id: 1
project_id: 2
joined_on: 2004-10-10
david_active_record:
developer_id: 1
project_id: 1
joined_on: 2004-10-10
jamis_active_record:
developer_id: 2
project_id: 1

View File

@ -0,0 +1,15 @@
class Project < ActiveRecord::Base
has_and_belongs_to_many :developers, :uniq => true
has_many :topics
# :finder_sql => 'SELECT * FROM topics WHERE (topics.project_id = #{id})',
# :counter_sql => 'SELECT COUNT(*) FROM topics WHERE (topics.project_id = #{id})'
has_many :replies, :through => :topics do
def find_recent(params = {})
with_scope :find => { :conditions => ['replies.created_at > ?', 15.minutes.ago] } do
find :all, params
end
end
end
end

View File

@ -0,0 +1,7 @@
action_controller:
id: 2
name: Active Controller
active_record:
id: 1
name: Active Record

View File

@ -0,0 +1,34 @@
witty_retort:
id: 1
topic_id: 1
content: Birdman is better!
created_at: <%= 6.hours.ago.to_s(:db) %>
updated_at: nil
another:
id: 2
topic_id: 2
content: Nuh uh!
created_at: <%= 1.hour.ago.to_s(:db) %>
updated_at: nil
spam:
id: 3
topic_id: 1
content: Nice site!
created_at: <%= 1.hour.ago.to_s(:db) %>
updated_at: nil
decisive:
id: 4
topic_id: 4
content: "I'm getting to the bottom of this"
created_at: <%= 30.minutes.ago.to_s(:db) %>
updated_at: nil
brave:
id: 5
topic_id: 4
content: "AR doesn't scare me a bit"
created_at: <%= 10.minutes.ago.to_s(:db) %>
updated_at: nil

View File

@ -0,0 +1,5 @@
class Reply < ActiveRecord::Base
belongs_to :topic, :include => [:replies]
validates_presence_of :content
end

View File

@ -0,0 +1,38 @@
ActiveRecord::Schema.define do
create_table "developers_projects", :id => false, :force => true do |t|
t.column "developer_id", :integer, :null => false
t.column "project_id", :integer, :null => false
t.column "joined_on", :date
t.column "access_level", :integer, :default => 1
end
create_table "projects", :force => true do |t|
t.column "name", :text
end
create_table "replies", :force => true do |t|
t.column "content", :text
t.column "created_at", :datetime
t.column "updated_at", :datetime
t.column "topic_id", :integer
end
create_table "topics", :force => true do |t|
t.column "project_id", :integer
t.column "title", :string
t.column "subtitle", :string
t.column "content", :text
t.column "created_at", :datetime
t.column "updated_at", :datetime
end
create_table "users", :force => true do |t|
t.column "name", :text
t.column "salary", :integer, :default => 70000
t.column "created_at", :datetime
t.column "updated_at", :datetime
t.column "type", :text
end
end

View File

@ -0,0 +1,4 @@
class Topic < ActiveRecord::Base
has_many :replies, :dependent => :destroy, :order => 'replies.created_at DESC'
belongs_to :project
end

View File

@ -0,0 +1,30 @@
futurama:
id: 1
title: Isnt futurama awesome?
subtitle: It really is, isnt it.
content: I like futurama
created_at: <%= 1.day.ago.to_s(:db) %>
updated_at:
harvey_birdman:
id: 2
title: Harvey Birdman is the king of all men
subtitle: yup
content: He really is
created_at: <%= 2.hours.ago.to_s(:db) %>
updated_at:
rails:
id: 3
project_id: 1
title: Rails is nice
subtitle: It makes me happy
content: except when I have to hack internals to fix pagination. even then really.
created_at: <%= 20.minutes.ago.to_s(:db) %>
ar:
id: 4
project_id: 1
title: ActiveRecord sometimes freaks me out
content: "I mean, what's the deal with eager loading?"
created_at: <%= 15.minutes.ago.to_s(:db) %>

View File

@ -0,0 +1,2 @@
class User < ActiveRecord::Base
end

View File

@ -0,0 +1,35 @@
david:
id: 1
name: David
salary: 80000
type: Developer
jamis:
id: 2
name: Jamis
salary: 150000
type: Developer
<% for digit in 3..10 %>
dev_<%= digit %>:
id: <%= digit %>
name: fixture_<%= digit %>
salary: 100000
type: Developer
<% end %>
poor_jamis:
id: 11
name: Jamis
salary: 9000
type: Developer
admin:
id: 12
name: admin
type: Admin
goofy:
id: 13
name: Goofy
type: Admin

View File

@ -0,0 +1,25 @@
require 'test/unit'
require 'rubygems'
# gem install redgreen for colored test output
begin require 'redgreen'; rescue LoadError; end
require File.join(File.dirname(__FILE__), 'boot') unless defined?(ActiveRecord)
class Test::Unit::TestCase
protected
def assert_respond_to_all object, methods
methods.each do |method|
[method.to_s, method.to_sym].each { |m| assert_respond_to object, m }
end
end
end
# Wrap tests that use Mocha and skip if unavailable.
def uses_mocha(test_name)
require 'mocha' unless Object.const_defined?(:Mocha)
yield
rescue LoadError => load_error
raise unless load_error.message =~ /mocha/i
$stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
end

View File

@ -0,0 +1,23 @@
require File.join(File.dirname(__FILE__), 'activerecord_test_connector')
class ActiveRecordTestCase < Test::Unit::TestCase
# Set our fixture path
if ActiveRecordTestConnector.able_to_connect
self.fixture_path = File.join(File.dirname(__FILE__), '..', 'fixtures')
self.use_transactional_fixtures = false
end
def self.fixtures(*args)
super if ActiveRecordTestConnector.connected
end
def run(*args)
super if ActiveRecordTestConnector.connected
end
# Default so Test::Unit::TestCase doesn't complain
def test_truth
end
end
ActiveRecordTestConnector.setup

View File

@ -0,0 +1,67 @@
require 'active_record'
require 'active_record/version'
require 'active_record/fixtures'
class ActiveRecordTestConnector
cattr_accessor :able_to_connect
cattr_accessor :connected
# Set our defaults
self.connected = false
self.able_to_connect = true
def self.setup
unless self.connected || !self.able_to_connect
setup_connection
load_schema
# require_fixture_models
Dependencies.load_paths.unshift(File.dirname(__FILE__) + "/../fixtures")
self.connected = true
end
rescue Exception => e # errors from ActiveRecord setup
$stderr.puts "\nSkipping ActiveRecord assertion tests: #{e}"
#$stderr.puts " #{e.backtrace.join("\n ")}\n"
self.able_to_connect = false
end
private
def self.setup_connection
if Object.const_defined?(:ActiveRecord)
defaults = { :database => ':memory:' }
ActiveRecord::Base.logger = Logger.new STDOUT if $0 == 'irb'
begin
options = defaults.merge :adapter => 'sqlite3', :timeout => 500
ActiveRecord::Base.establish_connection(options)
ActiveRecord::Base.configurations = { 'sqlite3_ar_integration' => options }
ActiveRecord::Base.connection
rescue Exception # errors from establishing a connection
$stderr.puts 'SQLite 3 unavailable; trying SQLite 2.'
options = defaults.merge :adapter => 'sqlite'
ActiveRecord::Base.establish_connection(options)
ActiveRecord::Base.configurations = { 'sqlite2_ar_integration' => options }
ActiveRecord::Base.connection
end
unless Object.const_defined?(:QUOTED_TYPE)
Object.send :const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')
end
else
raise "Can't setup connection since ActiveRecord isn't loaded."
end
end
def self.load_schema
ActiveRecord::Base.silence do
ActiveRecord::Migration.verbose = false
load File.dirname(__FILE__) + "/../fixtures/schema.rb"
end
end
def self.require_fixture_models
models = Dir.glob(File.dirname(__FILE__) + "/../fixtures/*.rb")
models = (models.grep(/user.rb/) + models).uniq
models.each { |f| require f }
end
end

View File

@ -0,0 +1,13 @@
dirname = File.dirname(__FILE__)
require File.join(dirname, '..', 'boot')
require File.join(dirname, 'activerecord_test_connector')
# setup the connection
ActiveRecordTestConnector.setup
# load all fixtures
fixture_path = File.join(dirname, '..', 'fixtures')
Fixtures.create_fixtures(fixture_path, ActiveRecord::Base.connection.tables)
require 'will_paginate'
WillPaginate.enable_activerecord

View File

@ -0,0 +1,146 @@
require File.dirname(__FILE__) + '/helper'
require 'action_controller'
require 'action_controller/test_process'
ActionController::Routing::Routes.reload rescue nil
ActionController::Routing::Routes.draw do |map|
map.connect ':controller/:action/:id'
end
ActionController::Base.perform_caching = false
require 'will_paginate'
WillPaginate.enable_actionpack
class PaginationTest < Test::Unit::TestCase
class PaginationController < ActionController::Base
def list_developers
@options = params.delete(:options) || {}
@developers = (1..11).to_a.paginate(
:page => params[@options[:param_name] || :page] || 1,
:per_page => params[:per_page] || 4
)
render :inline => '<%= will_paginate @developers, @options %>'
end
protected
def rescue_errors(e) raise e end
def rescue_action(e) raise e end
end
def setup
@controller = PaginationController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
super
end
def test_will_paginate
get :list_developers
entries = assigns :developers
assert entries
assert_equal 4, entries.size
assert_select 'div.pagination', 1, 'no main DIV' do |el|
assert_select 'a[href]', 3 do |elements|
validate_page_numbers [2,3,2], elements
assert_select elements.last, ':last-child', "Next &raquo;"
end
assert_select 'span', 2
assert_select 'span.disabled:first-child', "&laquo; Previous"
assert_select 'span.current', entries.current_page.to_s
end
end
def test_will_paginate_with_options
get :list_developers, :page => 2, :options => {
:class => 'will_paginate', :prev_label => 'Prev', :next_label => 'Next'
}
assert_response :success
entries = assigns :developers
assert entries
assert_equal 4, entries.size
assert_select 'div.will_paginate', 1, 'no main DIV' do
assert_select 'a[href]', 4 do |elements|
validate_page_numbers [nil,nil,3,3], elements
assert_select elements.first, 'a', "Prev"
assert_select elements.last, 'a', "Next"
end
assert_select 'span.current', entries.current_page.to_s
end
end
def test_will_paginate_preserves_parameters
get :list_developers, :foo => { :bar => 'baz' }
assert_response :success
assert_select 'div.pagination', 1, 'no main DIV' do
assert_select 'a[href]', 3 do |elements|
elements.each do |el|
assert_match /foo%5Bbar%5D=baz/, el['href'], "THIS IS A BUG in Rails 1.2 which " +
"has been fixed in Rails 2.0."
# there is no need to worry *unless* you too are using hashes in parameters which
# need to be preserved over pages
end
end
end
end
def test_will_paginate_with_custom_page_param
get :list_developers, :developers_page => 2, :options => { :param_name => :developers_page }
assert_response :success
entries = assigns :developers
assert entries
assert_equal 4, entries.size
assert_select 'div.pagination', 1, 'no main DIV' do
assert_select 'a[href]', 4 do |elements|
validate_page_numbers [nil,nil,3,3], elements, :developers_page
end
assert_select 'span.current', entries.current_page.to_s
end
end
def test_will_paginate_windows
get :list_developers, :page => 6, :per_page => 1, :options => { :inner_window => 2 }
assert_response :success
entries = assigns :developers
assert entries
assert_equal 1, entries.size
assert_select 'div.pagination', 1, 'no main DIV' do
assert_select 'a[href]', 10 do |elements|
validate_page_numbers [5,nil,2,4,5,7,8,10,11,7], elements
assert_select elements.first, 'a', "&laquo; Previous"
assert_select elements.last, 'a', "Next &raquo;"
end
assert_select 'span.current', entries.current_page.to_s
end
end
def test_no_pagination
get :list_developers, :per_page => 12
entries = assigns :developers
assert_equal 1, entries.page_count
assert_equal 11, entries.size
assert_equal '', @response.body
end
protected
def validate_page_numbers expected, links, param_name = :page
assert_equal(expected, links.map { |e|
e['href'] =~ /\W#{param_name}=([^&]*)/
$1 ? $1.to_i : $1
})
end
end