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



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/cooperator/context.rb', line 47

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



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

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

#[]=(key, value) ⇒ Object



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

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
# File 'lib/cooperator/context.rb', line 19

def failure!(messages = {})
  messages.each do |key, message|
    errors[key].push message
  end

  self[:_failure] = true
end

#failure?Boolean

Returns:

  • (Boolean)


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

def failure?
  self[:_failure]
end

#include?(key) ⇒ Boolean

Returns:

  • (Boolean)


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

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

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

Returns:

  • (Boolean)


68
69
70
71
72
73
# File 'lib/cooperator/context.rb', line 68

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:

  • (Boolean)


27
28
29
# File 'lib/cooperator/context.rb', line 27

def success?
  not failure?
end