Class: Cooperator::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/cooperator/context.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Context

Returns a new instance of Context.



3
4
5
6
7
8
9
# File 'lib/cooperator/context.rb', line 3

def initialize(attributes = {})
  @_attributes = {_failure: false}

  attributes.each do |k, v|
    self[k] = v
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/cooperator/context.rb', line 51

def method_missing(method, *args, &block)
  if @_attributes.include? method
    puts Kernel.caller.first
    warn '[DEPRECATED] Cooperator::Context: Use hash-style accessors instead of methods.'

    return @_attributes.fetch method
  end

  name = String method

  if name.include? '='
    warn '[DEPRECATED] Cooperator::Context: Use hash-style accessors instead of methods.'

    name.gsub!(/=/, '')

    @_attributes[:"#{name}"] = args.shift
  else
    super
  end
end

Instance Method Details

#[](key) ⇒ Object



47
48
49
# File 'lib/cooperator/context.rb', line 47

def [](key)
  @_attributes[key]
end

#[]=(key, value) ⇒ Object



43
44
45
# File 'lib/cooperator/context.rb', line 43

def []=(key, value)
  @_attributes[key] = value
end

#errorsObject



11
12
13
# File 'lib/cooperator/context.rb', line 11

def errors
  @_errors ||= Hash.new { |h, k| h[k] = [] }
end

#failure!(messages = {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/cooperator/context.rb', line 19

def failure!(messages = {})
  messages.each do |key, message|
    if message.is_a? Array
      errors[key].push *message
    else
      errors[key].push message
    end
  end

  self[:_failure] = true
end

#failure?Boolean

Returns:



35
36
37
# File 'lib/cooperator/context.rb', line 35

def failure?
  self[:_failure]
end

#include?(key) ⇒ Boolean

Returns:



39
40
41
# File 'lib/cooperator/context.rb', line 39

def include?(key)
  @_attributes.include? key
end

#respond_to_missing?(method, private = false) ⇒ Boolean

Returns:



72
73
74
75
76
77
# File 'lib/cooperator/context.rb', line 72

def respond_to_missing?(method, private = false)
  name = String method
  name.gsub!(/=/, '') if name.include? '='

  @_attributes.include?(:"#{name}") || super
end

#success!Object



15
16
17
# File 'lib/cooperator/context.rb', line 15

def success!
  self[:_failure] = false
end

#success?Boolean

Returns:



31
32
33
# File 'lib/cooperator/context.rb', line 31

def success?
  not failure?
end