• Stars
    star
    1,026
  • Rank 44,887 (Top 0.9 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 17 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Treat an ActiveRecord model as a file attachment, storing its patch, size, content type, etc.
attachment-fu
=============

attachment_fu is a plugin by Rick Olson (aka technoweenie <http://techno-weenie.net>) and is the successor to acts_as_attachment.  To get a basic run-through of its capabilities, check out Mike Clark's tutorial <http://clarkware.com/cgi/blosxom/2007/02/24#FileUploadFu>.


attachment_fu functionality
===========================

attachment_fu facilitates file uploads in Ruby on Rails.  There are a few storage options for the actual file data, but the plugin always at a minimum stores metadata for each file in the database.

There are four storage options for files uploaded through attachment_fu:
  File system
  Database file
  Amazon S3
  Rackspace (Mosso) Cloud Files

Each method of storage many options associated with it that will be covered in the following section.  Something to note, however, is that the Amazon S3 storage requires you to modify config/amazon_s3.yml, the Rackspace Cloud Files storage requires you to modify config/rackspace_cloudfiles.yml, and the Database file storage requires an extra table.


attachment_fu models
====================

For all three of these storage options a table of metadata is required.  This table will contain information about the file (hence the 'meta') and its location.  This table has no restrictions on naming, unlike the extra table required for database storage, which must have a table name of db_files (and by convention a model of DbFile).
  
In the model there are two methods made available by this plugins: has_attachment and validates_as_attachment.

has_attachment(options = {})
  This method accepts the options in a hash:
    :content_type     # Allowed content types.
                      # Allows all by default.  Use :image to allow all standard image types.
    :min_size         # Minimum size allowed.
                      # 1 byte is the default.
    :max_size         # Maximum size allowed.
                      # 1.megabyte is the default.
    :size             # Range of sizes allowed.
                      # (1..1.megabyte) is the default.  This overrides the :min_size and :max_size options.
    :resize_to        # Used by RMagick to resize images.
                      # Pass either an array of width/height, or a geometry string.
    :thumbnails       # Specifies a set of thumbnails to generate.
                      # This accepts a hash of filename suffixes and RMagick resizing options.
                      # This option need only be included if you want thumbnailing.
    :thumbnail_class  # Set which model class to use for thumbnails.
                      # This current attachment class is used by default.
    :path_prefix      # Path to store the uploaded files in.
                      # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 and Cloud Files backend.  
                      # Setting this sets the :storage to :file_system.
    :partition        # Whether to partiton files in directories like /0000/0001/image.jpg. Default is true. Only applicable to the :file_system backend.
    :storage          # Specifies the storage system to use..
                      # Defaults to :db_file.  Options are :file_system, :db_file, :s3, and :cloud_files.
    :cloudfront       # If using S3 for storage, this option allows for serving the files via Amazon CloudFront.
                      # Defaults to false.
    :processor        # Sets the image processor to use for resizing of the attached image.
                      # Options include ImageScience, Rmagick, and MiniMagick.  Default is whatever is installed.
    :uuid_primary_key # If your model's primary key is a 128-bit UUID in hexadecimal format, then set this to true.
    :association_options  # attachment_fu automatically defines associations with thumbnails with has_many and belongs_to. If there are any additional options that you want to pass to these methods, then specify them here.
    

  Examples:
    has_attachment :max_size => 1.kilobyte
    has_attachment :size => 1.megabyte..2.megabytes
    has_attachment :content_type => 'application/pdf'
    has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
    has_attachment :content_type => :image, :resize_to => [50,50]
    has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
    has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
    has_attachment :storage => :file_system, :path_prefix => 'public/files'
    has_attachment :storage => :file_system, :path_prefix => 'public/files', 
                   :content_type => :image, :resize_to => [50,50], :partition => false
    has_attachment :storage => :file_system, :path_prefix => 'public/files',
                   :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
    has_attachment :storage => :s3
    has_attachment :store => :s3, :cloudfront => true
    has_attachment :storage => :cloud_files

validates_as_attachment
  This method prevents files outside of the valid range (:min_size to :max_size, or the :size range) from being saved.  It does not however, halt the upload of such files.  They will be uploaded into memory regardless of size before validation.
  
  Example:
    validates_as_attachment


attachment_fu migrations
========================

Fields for attachment_fu metadata tables...
  in general:
    size,         :integer  # file size in bytes
    content_type, :string   # mime type, ex: application/mp3
    filename,     :string   # sanitized filename
  that reference images:
    height,       :integer  # in pixels
    width,        :integer  # in pixels
  that reference images that will be thumbnailed:
    parent_id,    :integer  # id of parent image (on the same table, a self-referencing foreign-key).
                            # Only populated if the current object is a thumbnail.
    thumbnail,    :string   # the 'type' of thumbnail this attachment record describes.  
                            # Only populated if the current object is a thumbnail.
                            # Usage:
                            # [ In Model 'Avatar' ]
                            #   has_attachment :content_type => :image, 
                            #                  :storage => :file_system, 
                            #                  :max_size => 500.kilobytes,
                            #                  :resize_to => '320x200>',
                            #                  :thumbnails => { :small => '10x10>',
                            #                                   :thumb => '100x100>' }
                            # [ Elsewhere ]
                            # @user.avatar.thumbnails.first.thumbnail #=> 'small'
  that reference files stored in the database (:db_file):
    db_file_id,   :integer  # id of the file in the database (foreign key)
    
Field for attachment_fu db_files table:
  data, :binary # binary file data, for use in database file storage


attachment_fu views
===================

There are two main views tasks that will be directly affected by attachment_fu: upload forms and displaying uploaded images.

There are two parts of the upload form that differ from typical usage.
  1. Include ':multipart => true' in the html options of the form_for tag.
    Example:
      <% form_for(:attachment_metadata, :url => { :action => "create" }, :html => { :multipart => true }) do |form| %>
      
  2. Use the file_field helper with :uploaded_data as the field name.
    Example:
      <%= form.file_field :uploaded_data %>

Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system, s3, and Cloud Files storage.

public_filename(thumbnail = nil)
  Returns the public path to the file.  If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail.
  Examples:
    attachment_obj.public_filename          #=> /attachments/2/file.jpg
    attachment_obj.public_filename(:thumb)  #=> /attachments/2/file_thumb.jpg
    attachment_obj.public_filename(:small)  #=> /attachments/2/file_small.jpg

When serving files from database storage, doing more than simply downloading the file is beyond the scope of this document.


attachment_fu controllers
=========================

There are two considerations to take into account when using attachment_fu in controllers.

The first is when the files have no publicly accessible path and need to be downloaded through an action.

Example:
  def readme
    send_file '/path/to/readme.txt', :type => 'plain/text', :disposition => 'inline'
  end
  
See the possible values for send_file for reference.


The second is when saving the file when submitted from a form.
Example in view:
 <%= form.file_field :attachable, :uploaded_data %>

Example in controller:
  def create
    @attachable_file = AttachmentMetadataModel.new(params[:attachable])
    if @attachable_file.save
      flash[:notice] = 'Attachment was successfully created.'
      redirect_to attachable_url(@attachable_file)     
    else
      render :action => :new
    end
  end

attachement_fu scripting
====================================

You may wish to import a large number of images or attachments. 
The following example shows how to upload a file from a script. 

#!/usr/bin/env ./script/runner

# required to use ActionController::TestUploadedFile 
require 'action_controller'
require 'action_controller/test_process.rb'

path = "./public/images/x.jpg"

# mimetype is a string like "image/jpeg". One way to get the mimetype for a given file on a UNIX system
# mimetype = `file -ib #{path}`.gsub(/\n/,"")

mimetype = "image/jpeg"

# This will "upload" the file at path and create the new model.
@attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype))
@attachable.save

More Repositories

1

restful-authentication

inactive project
Ruby
1,573
star
2

coffee-resque

CoffeeScript
545
star
3

guillotine

URL shortening hobby kit
Ruby
485
star
4

twitter-node

Discontinued: check out nTwitter
JavaScript
445
star
5

acts_as_versioned

ActiveRecord plugin for versioning your models.
Ruby
408
star
6

permalink_fu

ActiveRecord plugin for automatically converting fields to permalinks.
Ruby
264
star
7

masochism

ActiveRecord connection proxy for master/slave connections
Ruby
248
star
8

grohl

Combination logging, exception reporting, and metrics library for Go.
Go
165
star
9

madrox

Distributed Twitter implementation in Git.
Ruby
153
star
10

nubnub

Node.js PubSubHubbub client/server implementation
CoffeeScript
144
star
11

jquery.doubletap

This jquery plugin adds custom touch-screen events to the given HTML elements.
JavaScript
137
star
12

wheres-waldo

track what users are on which pages with redis
JavaScript
119
star
13

cronwtf

silly cron => english translator
JavaScript
94
star
14

can_search

Build common named scopes automatically, and provide a simple way to merge them with a single #search call.
Ruby
93
star
15

node-scoped-http-client

Unmaintained. Free push/npm access to anyone interested.
CoffeeScript
84
star
16

node-chain-gang

CoffeeScript
81
star
17

serialized_attributes

kind of a bridge between using AR and a full blown schema-free db
Ruby
61
star
18

model_stubbing

Replacement for ActiveRecord fixtures using an extremely flexible ruby-based approach.
Ruby
55
star
19

viking

Discontinued, see https://github.com/dimelo/viking
Ruby
53
star
20

go-scientist

Go
49
star
21

faraday-zeromq

Ruby
47
star
22

relative_time_helpers

ActionView helpers for showing relative time spans like "Jan 1 - 5" or "Jan 1 - Feb 5"
Ruby
45
star
23

multipartstreamer

Go
44
star
24

sentry

Painless encryption wrapper library
Ruby
32
star
25

model_iterator

Ruby
32
star
26

twitter-server

ruby/sinatra extensions for implementing the twitter api
Ruby
31
star
27

yajl-rails

Rails plugin for using YAJL with Rails 3
Ruby
29
star
28

app_bootstrap

app:bootstrap rake task providing a command line menu to setup a rails app.
Ruby
29
star
29

emoji-css-builder

Quick Ruby rake task for generating CSS and tiled image for displaying emoji in browsers.
Ruby
29
star
30

sparkplug

Ruby Rack module for generating sparkline graphs on the fly
Ruby
26
star
31

astrotrain

email => http_post
Ruby
26
star
32

duplikate

Syncs one directory to another (example: a git project to an svn repo)
Ruby
25
star
33

running_man

Ruby
23
star
34

dealer.js

JavaScript
21
star
35

chat_gram

Barebones Instagram realtime endpoint for posting images to a chat service (Campfire).
Ruby
19
star
36

github_twitter_server

wrap github with a twitter api.
Ruby
18
star
37

islostonyet.com

no really, i need to know
Ruby
18
star
38

will_sign

Small module for creating time-based hashes based on URLs.
Ruby
17
star
39

horcrux

A Horcrux is a powerful object in which a Dark wizard or witch has hidden a fragment of his or her soul for the purpose of attaining immortality.
Ruby
16
star
40

weatherhue

Ruby
13
star
41

queue_kit

Ruby
11
star
42

zcollab

Rad ZeroMQ scripts to supercharge your cloud.
JavaScript
11
star
43

context_on_crack

experimental macros for testing rails controllers. port of rspec_on_rails_on_crack
11
star
44

ultraviolence

web service for formatting text with the ultraviolet lib. ruby 1.9 only
Ruby
10
star
45

schemagram

Generate JSON Schema files from Ruby.
Ruby
9
star
46

go-httppipe

Go
9
star
47

service-queue

experimental ZeroMQ task worker thing.
CoffeeScript
9
star
48

activesupport_notifications_backport

Ruby
9
star
49

httpretry

Go
9
star
50

flappy-atom

CoffeeScript
8
star
51

urban_api

quick and dirty urban dictionary scraper
Ruby
8
star
52

dangerroom

Go
7
star
53

git-nosql-talk

Git is a Stupid NOSQL Database - talk given at Ruby and Rails.eu 2010
Ruby
7
star
54

rack-sparklines

DISCONTINUED, SEE http://github.com/technoweenie/sparkplug
Ruby
7
star
55

markup_cloud

Render text into markup through local and zeromq endpoints
Ruby
7
star
56

coffee-sprites

simple html 5 animation/sprites system heavily inspired by http://gamesinhtml5.blogspot.com/2010/07/game-in-progress-sprites-and-animation.html
JavaScript
6
star
57

go-contentaddressable

Go
5
star
58

unique_content_set

Check for uniquely created content in a Redis set
Ruby
5
star
59

elixir-rubyports

Elixir
5
star
60

fantomex

[ALPHA] Small, per-process persistent queue.
CoffeeScript
4
star
61

camo.go

Go
4
star
62

http_token_authentication

Rails plugin for parsing http token authorization headers
Ruby
4
star
63

active_record_context

simple identity map for active record. eager loading associations FTL
Ruby
4
star
64

go-passthrough

Simple package for passing responses untouched from an internal API
Go
4
star
65

pylists

Python
4
star
66

zue

Ruby
4
star
67

pki

Ruby
4
star
68

rubysweetsixteen

i'm probably jumping the shark by posting this...
Ruby
4
star
69

lighthouse-notifier

Ruby
3
star
70

ud

Ruby
3
star
71

15

3
star
72

redis_active_set

Tracks the number of active objects during a certain time period in a Redis sorted set.
Ruby
3
star
73

guillotine-zeromq

ZeroMQ API for Guillotine
Ruby
2
star
74

hubot-zeromq

proof-of-concept zeromq adapter for Hubot
CoffeeScript
2
star
75

apub

experimental golang package for parsing ActivityPub objects
Go
2
star
76

pdxjs-twitter-node

JavaScript
2
star
77

fantomex.rb

[ALPHA] Small, per-process persistent queue.
Ruby
1
star
78

tender_sync

sync Tender FAQs to and from Tender
Ruby
1
star
79

dummy-repo

1
star
80

playground

1
star
81

go-ronn

Go
1
star