50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
# File 'lib/papermill/papermill.rb', line 50
def papermill(assoc_key, assoc_options = (@papermill_options && @papermill_options[:default] || {}))
return if @papermill_options && @papermill_options[assoc_key.to_sym] raise PapermillException.new("Can't use '#{assoc_key}' association : #{self.name} instances already responds to it !") if self.new.respond_to?(assoc_key)
(@papermill_options ||= {}).merge!( { assoc_key.to_sym => Papermill::options.deep_merge(assoc_options) } )
return if assoc_key.to_sym == :default
unless papermill_options[assoc_key.to_sym][:through]
self.class_eval %{
has_many :#{assoc_key}, :as => "assetable", :dependent => :destroy, :order => :position, :class_name => "PapermillAsset", :conditions => {:assetable_key => '#{assoc_key}'}, :before_add => Proc.new{|a, asset| asset.assetable_key = '#{assoc_key}'}
def papermill_#{assoc_key}_ids=(ids)
unless (assets_ids = ids.map(&:to_i).select{|i|i>0}) == self.#{assoc_key}.map(&:id)
assets = PapermillAsset.find(assets_ids)
self.#{assoc_key} = assets_ids.map{|asset_id| assets.select{|asset|asset.id==asset_id}.first}
PapermillAsset.update_all("position = CASE id " + assets_ids.map_with_index{|asset_id, index| " WHEN " + asset_id.to_s + " THEN " + (index+1).to_s }.join + " END",
:id => assets_ids) unless assets_ids.empty?
end
end
}
else
self.class_eval %{
has_many(:#{assoc_key}_associations, :as => "assetable", :class_name => "PapermillAssociation", :include => :papermill_asset, :dependent => :delete_all, :order => :position, :conditions => {:assetable_key => '#{assoc_key}'}, :before_add => Proc.new{|a, assoc| assoc.assetable_key = '#{assoc_key}'})
has_many(:#{assoc_key}, :through => :#{assoc_key}_associations, :source => :papermill_asset)
def papermill_#{assoc_key}_ids=(ids)
unless (assets_ids = ids.map(&:to_i).select{|i|i>0}) == self.#{assoc_key}_associations.map(&:papermill_asset_id)
self.#{assoc_key}_associations.delete_all
self.#{assoc_key}_associations = assets_ids.map_with_index do |asset_id, index|
PapermillAssociation.new(:papermill_asset_id => asset_id, :position => (index+1))
end
end
end
}
end
end
|