Sha256: c8d51caf6a890f924cc192dceebbe9200780b7be23f20320554ed77843ea2a40

Contents?: true

Size: 1.81 KB

Versions: 6

Compression:

Stored size: 1.81 KB

Contents

# encoding: UTF-8
module Amalgam
  module Models
    module Attachable
      extend ActiveSupport::Concern

      included do
        attr_accessible :attachments_attributes
        has_many :attachments, :as => :attachable, :class_name => Amalgam.attachment_class_name, :extend => ::Amalgam::Models::Attachable::AttachmentExtension
        accepts_nested_attributes_for :attachments,
          :allow_destroy => true,
          :reject_if => proc {|attachment| attachment[:id].blank? && attachment[:file].blank?}
      end

      module AttachmentExtension
        class DelegateArray < ::Array
          def method_missing(*args)
            first.send(*args)
          end
        end


        # 返回一个 <tt>#HashWithIndifferentAccess</tt>
        # 包含所有的附件,key为附件的name或者索引, value 为集合, 可直接作为第一个元素调用
        # 举例:
        #  page[:attachments]
        #  # => [{:name => 'file' , :file => <FILE1> },
        #  #     {:name => 'file} , :file => <FILE2> },
        #  #     {:name => 'file2', :file => <FILE3>}
        #  #     {:file => <FILE4>}]
        #  page.attachments
        #  #  => {0 => <FILE1> , 1 => <FILE2> , 2 => <FILE3> ,3 => <FILE4>
        #         'file' => [<FILE1>,<FILE2>],
        #         'file2' => [<FILE3>]
        #        }
        #  page.attachments['file'].name #=> page.attachments['file'].first.name
        def [](key)
          return @attachments_hash[key] if @attachments_hash
          @attachments_hash = HashWithIndifferentAccess.new
          each_with_index do |a,i|
            @attachments_hash[i] = a
            if a.name.present?
              @attachments_hash[a.name] = (@attachments_hash[a.name] || DelegateArray.new) << a
            end
          end
          @attachments_hash[key]
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
amalgam-2.1.4.1 lib/amalgam/models/attachable.rb
amalgam-2.1.4 lib/amalgam/models/attachable.rb
amalgam-2.1.3.1 lib/amalgam/models/attachable.rb
amalgam-2.1.3 lib/amalgam/models/attachable.rb
amalgam-2.1.2 lib/amalgam/models/attachable.rb
amalgam-2.1.1 lib/amalgam/models/attachable.rb