Module: StaticRecord::GatewayModel

Included in:
Base
Defined in:
lib/static_record/gateway_model.rb

Overview

The main gate for the model class methods.

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *params, &block) ⇒ Object (private)



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/static_record/gateway_model.rb', line 59

def method_missing(meth, *params, &block)
  attribute = meth.to_s.gsub(/=$/, '')

  if meth.to_s =~ /^find_by_(.+)/
    attribute = meth.to_s.gsub(/^find_by_/, '')

    return find_by(attribute.to_sym => params.first)
  elsif records.respond_to? attribute.to_sym
    # The method missing is part of Array object, try pass it
    return array_proxy attribute.to_sym, params unless meth.to_s =~ /=$/
  end

  super
end

Instance Method Details

#allObject



4
5
6
# File 'lib/static_record/gateway_model.rb', line 4

def all
  records
end

#find(*ids) ⇒ Object

Raises:



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/static_record/gateway_model.rb', line 8

def find(*ids)
  context = records.select { |c| ids.include? c.id }

  raise RecordNotFound.new(
    "Couldn't find #{to_s.tableize} with an out of range value for id.",
    to_s.tableize,
    'id'
  ) if context.empty?

  return context.first if context.length == 1
  context
end

#find_by(hash) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/static_record/gateway_model.rb', line 21

def find_by(hash)
  unless hash.is_a? Hash
    raise InvalidParameterError,
          'Couldn\'t find record, because search closure is not a Hash.'
  end

  key, value = hash.first

  context = records.select { |c| c.attributes[key] == value }

  return context.first if context.length == 1
  context
end

#find_by!(hash) ⇒ Object

Raises:



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/static_record/gateway_model.rb', line 35

def find_by!(hash)
  context = find_by hash
  key, value = hash.first

  raise RecordNotFound.new(
    "Couldn't find #{to_s.tableize} like #{key} as #{value}",
    to_s.tableize,
    'id'
  ) if context.empty?
  context
end