Class: Radar::Config::UseArray

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/radar/config.rb

Overview

A subclass of Array which allows for slightly different usage, based on ActionDispatch::MiddlewareStack in Rails 3. The main methods are enumerated below:

Instance Method Summary collapse

Constructor Details

#initialize(*args, &block) ⇒ UseArray

Initializes the UseArray with the given block used to generate the value created for the #use method. The block given determines how the #use method stores the key/value.



202
203
204
205
# File 'lib/radar/config.rb', line 202

def initialize(*args, &block)
  @_array = []
  @_use_block = block || Proc.new { |key, *args| [key, key] }
end

Instance Method Details

#delete(key) ⇒ Object

Delete the object with the given key or index.



238
239
240
# File 'lib/radar/config.rb', line 238

def delete(key)
  @_array.delete_at(index(key))
end

#index(key) ⇒ Object

Returns the value for the given key. If the key is an integer, it is returned as-is. Otherwise, do a lookup on the array for the the given key and return the index of it.



245
246
247
248
249
250
251
252
# File 'lib/radar/config.rb', line 245

def index(key)
  return key if key.is_a?(Integer)
  @_array.each_with_index do |data, i|
    return i if data[0] == key
  end

  nil
end

#insert(key, *args, &block) ⇒ Object Also known as: insert_before

Insert the given key at the given index or directly before the given object (by key).



215
216
217
218
# File 'lib/radar/config.rb', line 215

def insert(key, *args, &block)
  args.push(block) if block
  @_array.insert(index(key), @_use_block.call(*args))
end

#insert_after(key, *args, &block) ⇒ Object

Insert after the given key.

Raises:

  • (ArgumentError)


222
223
224
225
226
# File 'lib/radar/config.rb', line 222

def insert_after(key, *args, &block)
  i = index(key)
  raise ArgumentError.new("No such key found: #{key}") if !i
  insert(i + 1, *args, &block)
end

#swap(key, *args, &block) ⇒ Object

Swaps out the given object at the given index or key with a new object.

Raises:

  • (ArgumentError)


230
231
232
233
234
235
# File 'lib/radar/config.rb', line 230

def swap(key, *args, &block)
  i = index(key)
  raise ArgumentError.new("No such key found: #{key}") if !i
  delete(i)
  insert(i, *args, &block)
end

#use(*args, &block) ⇒ Object

Use the given key. It is up to the configured use block (given by the initializer) to generate the actual key/value stored in the array.



209
210
211
# File 'lib/radar/config.rb', line 209

def use(*args, &block)
  insert(length, *args, &block)
end

#valuesObject

Returns the values of this array.



255
256
257
258
259
260
# File 'lib/radar/config.rb', line 255

def values
  @_array.inject([]) do |acc, data|
    acc << data[1]
    acc
  end
end