Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion lib/refile/mongoid/attachment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,49 @@ def attachment(name, raise_errors: false, **options)
end
end
end

end

def accepts_attachments_for(association_name, attachment: :file, append: false)
association = reflect_on_association(association_name)
name = "#{association_name}_#{attachment.to_s.pluralize}"

mod = Module.new do
define_method :"#{name}_attachment_definition" do
association.klass.send("#{attachment}_attachment_definition")
end

define_method :"#{name}_data" do
if send(association_name).all? { |record| record.send("#{attachment}_attacher").valid? }
send(association_name).map(&:"#{attachment}_data").select(&:present?)
end
end

define_method :"#{name}" do
send(association_name).map(&attachment)
end

define_method :"#{name}=" do |files|
cache, files = files.partition { |file| file.is_a?(String) }

cache = Refile.parse_json(cache.first)

if not append and (files.present? or cache.present?)
send("#{association_name}=", [])
end

if files.empty? and cache.present?
cache.select(&:present?).each do |file|
send(association_name).build(attachment => file.to_json)
end
else
files.select(&:present?).each do |file|
send(association_name).build(attachment => file)
end
end
end
end

include mod
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion refile-mongoid.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Gem::Specification.new do |gem|
gem.require_path = "lib"

gem.add_dependency "refile", "~> 0.5"
gem.add_dependency 'mongoid', '~> 4.0'
gem.add_dependency 'mongoid', '>= 4.0'

gem.add_development_dependency "rake", "~> 10.0"
gem.add_development_dependency "rspec", "~> 3.1"
Expand Down