Module: Amalgam::Models::Attachable::AttachmentExtension

Defined in:
lib/amalgam/models/attachable.rb

Defined Under Namespace

Classes: DelegateArray

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object

返回一个 #HashWithIndifferentAccess 包含所有的附件,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


37
38
39
40
41
42
43
44
45
46
47
# File 'lib/amalgam/models/attachable.rb', line 37

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