From a7ac0e07efc41eaa2d7cc6bc65f45e8426b152f8 Mon Sep 17 00:00:00 2001 From: Sergey Kishenin Date: Fri, 23 Oct 2015 03:59:12 +0600 Subject: [PATCH 1/2] Add support for accepts_attachments_for method The implementation is the same as for ActiveRecord. Close #1 --- lib/refile/mongoid/attachment.rb | 44 +++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/lib/refile/mongoid/attachment.rb b/lib/refile/mongoid/attachment.rb index aff5504..55a7dfc 100644 --- a/lib/refile/mongoid/attachment.rb +++ b/lib/refile/mongoid/attachment.rb @@ -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 From 336d164ea8ce5bd25d9519e81465da84c7b3e140 Mon Sep 17 00:00:00 2001 From: Sergey Kishenin Date: Fri, 23 Oct 2015 04:07:49 +0600 Subject: [PATCH 2/2] Depend on Mongoid >= 4.0 --- refile-mongoid.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/refile-mongoid.gemspec b/refile-mongoid.gemspec index 9222591..b684a15 100644 --- a/refile-mongoid.gemspec +++ b/refile-mongoid.gemspec @@ -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"