Class: Contextuable
- Inherits:
-
Object
show all
- Defined in:
- lib/contextuable.rb
Overview
Defined Under Namespace
Classes: PresenceRequired, RequiredFieldNotPresent
Constant Summary
collapse
- VERSION =
extend Forwardable delegate :[], to: :args
"0.1.0"
Instance Attribute Summary collapse
-
#args ⇒ Object
(also: #to_h, #to_hash)
readonly
Returns the value of attribute args.
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(hash = {}) ⇒ Contextuable
Returns a new instance of Contextuable.
36
37
38
39
40
41
42
43
44
45
|
# File 'lib/contextuable.rb', line 36
def initialize(hash = {})
fail ArgumentError unless hash.respond_to?(:fetch)
fail RequiredFieldNotPresent unless _required_args.map(&:to_sym).all? { |r| hash.keys.map(&:to_sym).include?(r) }
fail PresenceRequired if _presence_required.map(&:to_sym).any? { |r| hash[r].nil? }
hash = hash.select{|k, v| _permitted.include?(k.to_sym) } if _only_permitted?
@args = _defaults.merge(hash)
args.each do |k, v|
define_special_method(k, v)
end
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
# File 'lib/contextuable.rb', line 55
def method_missing(name, *args, &block)
if ary = find_in_equivalents(name)
_from_equivalents(ary)
elsif name =~ /\A\w+=\z/
value = args.first || block
key = name.to_s.gsub('=', '').to_sym
set_attribute(key, value)
else
name.to_s.include?('?') ? false : nil
end
end
|
Instance Attribute Details
#args ⇒ Object
Also known as:
to_h, to_hash
Returns the value of attribute args.
32
33
34
|
# File 'lib/contextuable.rb', line 32
def args
@args
end
|
Class Method Details
.aliases(*names) ⇒ Object
18
19
20
21
|
# File 'lib/contextuable.rb', line 18
def aliases(*names)
@_equivalents ||= []
@_equivalents << names.map(&:to_sym)
end
|
.defaults(hash) ⇒ Object
23
24
25
|
# File 'lib/contextuable.rb', line 23
def defaults(hash)
@_defaults = hash
end
|
.ensure_presence(*names) ⇒ Object
14
15
16
|
# File 'lib/contextuable.rb', line 14
def ensure_presence(*names)
@_presence_required = names.map(&:to_sym)
end
|
.permit(*names) ⇒ Object
27
28
29
|
# File 'lib/contextuable.rb', line 27
def permit(*names)
@_permitted = names.map(&:to_sym)
end
|
.required(*names) ⇒ Object
10
11
12
|
# File 'lib/contextuable.rb', line 10
def required(*names)
@_required = names.map(&:to_sym)
end
|
Instance Method Details
#[](key) ⇒ Object
47
48
49
|
# File 'lib/contextuable.rb', line 47
def [](key)
args[key]
end
|
#[]=(key, value) ⇒ Object
51
52
53
|
# File 'lib/contextuable.rb', line 51
def []=(key, value)
set_attribute(key, value)
end
|