Class: Hyperactive::MatchSaver

Inherits:
Object
  • Object
show all
Defined in:
lib/hyperactive/record.rb

Overview

A tiny callable class that saves stuff inside containers if they match certain criteria.

Instance Method Summary collapse

Constructor Details

#initialize(key, matcher, mode) ⇒ MatchSaver

Initialize this MatchSaver with a key, a callable matcher and a mode (:select, :reject, :delete_if_match or :delete_unless_match).



88
89
90
91
92
# File 'lib/hyperactive/record.rb', line 88

def initialize(key, matcher, mode)
  @key = key
  @matcher = matcher
  @mode = mode
end

Instance Method Details

#call(argument, &block) ⇒ Object

Depending on @mode and return value of @matcher.call may save record in the Hash-like container named @key in the main database after having yielded to block.



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/hyperactive/record.rb', line 98

def call(argument, &block)
  yield

  record = argument
  record = argument.last if Array === argument

  case @mode
  when :select
    if @matcher.call(record)
      CAPTAIN[@key][record.record_id] = record
    else
      CAPTAIN[@key].delete(record.record_id)
    end
  when :reject
    if @matcher.call(record)
      CAPTAIN[@key].delete(record.record_id)
    else
      CAPTAIN[@key][record.record_id] = record
    end
  when :delete_if_match
    if @matcher.call(record)
      CAPTAIN[@key].delete(record.record_id)
    end
  when :delete_unless_match
    unless @matcher.call(record)
      CAPTAIN[@key].delete(record.record_id)
    end
  end
end