Created
March 22, 2010 10:11
-
-
Save fxposter/339940 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Asset < ActiveRecord::Base | |
belongs_to :owner, :polymorphic => true | |
class User < self | |
has_attached_file :image, :styles => { :original => "160x160>" } | |
before_create :destroy_previous_asset | |
end | |
protected | |
def destroy_previous_asset | |
unless owner_id.blank? | |
obj = self.class.find_by_owner_id_and_owner_type(owner_id, owner_type) | |
obj.destroy unless obj.nil? | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module HasAsset | |
def has_asset asset_name, options | |
has_one(asset_name, { :as => :owner, :dependent => :destroy }.merge(options)) | |
asset_name = asset_name.to_s | |
asset_class = options[:class_name].constantize | |
alias_method "#{asset_name}__old", asset_name | |
define_method asset_name do | |
@asset_vars ||= {} | |
send("#{asset_name}__old") || (@asset_vars[asset_name] ||= asset_class.new) | |
end | |
define_method "#{asset_name}_id=" do |new_value| | |
send("#{asset_name}=", asset_class.find(new_value)) unless new_value.blank? | |
end | |
define_method "#{asset_name}_url" do |style| | |
send(asset_name).image.url(style) | |
end | |
define_method "#{asset_name}?" do | |
send(asset_name).image? | |
end | |
end | |
end | |
ActiveRecord::Base.send(:extend, HasAsset) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
has_asset :logo, :class_name => "Asset::User" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment