Class: Array

Inherits:
Object
  • Object
show all
Includes:
CoreExtensions::Array::DuplicatesCounter
Defined in:
lib/ib/gateway.rb

Overview

module GWSupport provide AR4- ActiveRelation-like-methods to Array-Class refine Array do

Instance Method Summary collapse

Methods included from CoreExtensions::Array::DuplicatesCounter

#count_duplicates

Instance Method Details

#first_or_create(item, *condition, &b) ⇒ Object

returns the item (in case of first) or the hole array (in case of create)



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/ib/gateway.rb', line 12

def first_or_create item, *condition, &b
  int_array = if condition.empty? 
      [ find_all{ |x| x == item } ] if !block_given?
    else
      condition.map{ |c| find_all{|x| x[ c ] == item[ c ] }}
    end || []
  if block_given?
    relation = yield
    part_2 = find_all{ |x| x.send( relation ) == item.send( relation ) }
    int_array <<  part_2 unless part_2.empty?
  end
  # reduce performs a logical "&" between the array-elements
  # we are only interested in the first entry
  r= int_array.reduce( :& )
  r.present? ? r.first : self.push( item ) 
end

#interceptObject

performs [ [ array ] & [ array ] & [..] ].first



35
36
37
38
39
40
41
42
# File 'lib/ib/gateway.rb', line 35

def intercept
  a = self.dup
  s = a.pop
  while a.present?
    s = s & a.pop
  end
  s.first unless s.nil?  # return_value (or nil)
end

#update_or_create(item, *condition, &b) ⇒ Object



28
29
30
31
32
# File 'lib/ib/gateway.rb', line 28

def update_or_create item, *condition, &b
  member = first_or_create( item, *condition, &b) 
  self[ index( member ) ] = item  unless member.is_a?(Array)
  self  # always returns the array 
end