Module: Rubyfocus::Searchable

Included in:
Document, SearchableArray
Defined in:
lib/rubyfocus/includes/searchable.rb

Overview

The Searchable module allows you to easily search arrays of items by effectively supplying find and select methods. Passing a hash to either of these methods allows you to search by given properties - for example:

data_store.find(name: "Foobar")

Is basically the same as:

data_store.find{ |o| o.name == “Foobard” }

If you pass find or select a String or Fixnum, it will look for objects whose id equals this value.

You should ensure that your class’ array method is overwritten to point to the appriopriate array.

Instance Method Summary collapse

Instance Method Details

#arrayObject

This method should be overriden

Raises:

  • (RuntimeError)


42
43
44
# File 'lib/rubyfocus/includes/searchable.rb', line 42

def array
  raise RuntimeError, "Method #{self.class}#array has not been implemented!"
end

#find(arg = nil, &blck) ⇒ Object

This method will return only the first object that matches the given criteria, or nil if no object is found.



20
21
22
23
24
25
26
27
# File 'lib/rubyfocus/includes/searchable.rb', line 20

def find(arg=nil, &blck)
  fs_block = find_select_block(arg) || blck
  if fs_block
    return array.find(&fs_block)
  else
    raise ArgumentError, "ItemArray#find called with #{arg.class} argument."
  end
end

#select(arg = nil, &blck) ⇒ Object Also known as: find_all

This method will return an array of all objects that match the given criteria, or [] if no object is found.



31
32
33
34
35
36
37
38
# File 'lib/rubyfocus/includes/searchable.rb', line 31

def select(arg=nil, &blck)
  fs_block = find_select_block(arg) || blck
  if fs_block
    return array.select(&fs_block)
  else
    raise ArgumentError, "ItemArray#select called with #{arg.class} argument."
  end
end