Module: Fetchable

Included in:
Decorator
Defined in:
lib/fetchable.rb,
lib/fetchable/version.rb

Defined Under Namespace

Classes: Decorator

Constant Summary collapse

NO_DEFAULT_GIVEN =
Object.new
VERSION =
"1.0.0"

Instance Method Summary collapse

Instance Method Details

#fetch(key, not_found_value = NO_DEFAULT_GIVEN) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/fetchable.rb', line 4

def fetch(key, not_found_value = NO_DEFAULT_GIVEN)
  if not_found_value != NO_DEFAULT_GIVEN && block_given?
    raise ArgumentError.new("Cannot provide both a default arg and block to #fetch")
  end

  result = public_send(:[], key)

  if result.nil?
    return yield(key) if block_given?
    return not_found_value unless not_found_value == NO_DEFAULT_GIVEN

    raise KeyError.new("key not found #{key}")
  else
    result
  end
end