Class: Array::Reorder

Inherits:
Object
  • Object
show all
Includes:
Releaf::Service
Defined in:
app/services/array/reorder.rb

Instance Method Summary collapse

Instance Method Details

#callObject


35
36
37
38
39
40
41
42
43
44
# File 'app/services/array/reorder.rb', line 35

def call
  deleted_values = delete(values)
  index = reorder_index(options)

  values.reverse_each do|value|
    array.insert(index, deleted_values[value])
  end

  array
end

#delete(values) ⇒ Object


60
61
62
63
64
65
66
67
68
69
70
# File 'app/services/array/reorder.rb', line 60

def delete(values)
  deleted = {}

  values.each do|value|
    index = index(value)
    deleted[value] = array[index]
    array.delete_at(index)
  end

  deleted
end

#index(value) ⇒ Object


72
73
74
75
76
77
78
79
80
81
# File 'app/services/array/reorder.rb', line 72

def index(value)
  value = value.to_s
  array.index do |existing_value|
    if existing_value.is_a? Hash
      existing_value.keys.first.to_s == value
    else
      existing_value.to_s == value
    end
  end
end

#reorder_index(options) ⇒ Object


46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'app/services/array/reorder.rb', line 46

def reorder_index(options)
  if options == :first
    0
  elsif options == :last
    array.length
  elsif options[:after]
    index(options[:after]) + 1
  elsif options[:before]
    index(options[:before])
  else
    raise ArgumentError, "unknown reorder option"
  end
end

#values=(val) ⇒ Object


30
31
32
33
# File 'app/services/array/reorder.rb', line 30

def values=(val)
  val = [val] unless val.is_a? Array
  super
end