Module: Attachinary::Extension

Includes:
Base
Defined in:
lib/attachinary/orm/base_extension.rb,
lib/attachinary/orm/active_record/extension.rb

Defined Under Namespace

Modules: Base

Instance Method Summary collapse

Methods included from Base

#has_attachment, #has_attachments

Instance Method Details

#attachinary_orm_definition(options) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/attachinary/orm/active_record/extension.rb', line 7

def attachinary_orm_definition(options)
  relation = "#{options[:singular]}_files"

  # has_many :photo_files, ...
  # has_many :image_files, ...
  if Rails::VERSION::MAJOR == 3
    has_many :"#{relation}",
      as: :attachinariable,
      class_name: '::Attachinary::File',
      conditions: { scope: options[:scope].to_s },
      dependent: :destroy
  elsif Rails::VERSION::MAJOR > 3 && Rails::VERSION::MAJOR < 5
    has_many :"#{relation}",
             -> { where scope: options[:scope].to_s },
             as: :attachinariable,
             class_name: '::Attachinary::File',
             dependent: :destroy
  else
    has_many :"#{relation}",
      -> { where scope: options[:scope].to_s }, 
      as: :attachinariable,
      inverse_of: :attachinariable,
      class_name: '::Attachinary::File',
      dependent: :destroy
  end


  # def photo=(file)
  #   input = Attachinary::Utils.process_input(input, upload_options)
  #   if input.blank?
  #     photo_files.clear
  #   else
  #     files = [input].flatten
  #     self.photo_files = files
  #   end
  # end
  define_method "#{options[:scope]}=" do |input, upload_options = {}|
    input = Attachinary::Utils.process_input(input, upload_options, options[:scope])
    if input.nil?
      send("#{relation}").destroy_all
    else
      files = [input].flatten
      send("#{relation}=", files)
    end
  end


  if options[:single]
    # def photo
    #   photo_files.first
    # end
    define_method "#{options[:scope]}" do
      send("#{relation}").first
    end

  else # plural
    # def images
    #   image_files
    # end
    define_method "#{options[:scope]}" do
      send("#{relation}")
    end
  end

end