Reach Attachments And Some Metaprogramming, Too
The basic problem
•
Need to be able to attach arbitrary attachments to various model objects Don’t want to have to create new models for every relationship
•
Need to have multiple kinds of attachments on each model object
Basic Implementation •
Using attachment_fu as a base Basic Data Layout: •
attachment_fu stuff
•
attachable_id & attachable_type (polymorphic belongs_to) relationship (the relationship between the main model object and the attachment)
•
position - used for ordering
Things We Need
•
Easily add relationships Easily add the attachments from the controller
•
Easily create the input/view boxes on the view
The Interface •
Model: reach_single_attachment :relationship_name Controller: @model_obj.attach_relationship_name(par ams[:file_field_name])
•
View: •
<%= file_field :file_field_name %>
•
<%= link_to_attachment “View”, @model_obj.relationship_name %>
The Metaprogram
module ActiveRecord class Base def self.reach_single_attachment(relationship) has_one relationship, :as => :attachable, :class_name => "Attachment", :conditions => "relationship = '#{relationship}'", :dependent => :destroy define_method("attach_#{relationship}") do |file_field| if file_field.size > 0 new_relationship_obj = self.send("create_#{relationship}", :uploaded_data => file_field, :relationship => relationship.to_s) return new_relationship_obj end end end end end
Usage in Reach Models
cord::Base
nity_map reach_single_attachment :community_video re
Using Metaprogramming
•
Allows you to generalize in wierd ways Allows you to automate common tasks
•
Allows you to codify application-specific conventions