Class: Contextuable

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

Defined Under Namespace

Classes: PresenceRequired, RequiredFieldNotPresent, WrongArgument

Constant Summary collapse

VERSION =
"0.2.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Contextuable

Returns a new instance of Contextuable.



35
36
37
38
39
40
41
42
# File 'lib/contextuable.rb', line 35

def initialize(hash = {})
  check_input_errors(hash)
  hash = hash.select{|k, v| _permitted.include?(k.to_sym) } if _only_permitted?
  @args = _defaults.merge(hash)
  args.each do |k, v|
    define_contextuable_method(k, v)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/contextuable.rb', line 52

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
    case name.to_s
    when /\A\w+_not_provided\?\z/ then true
    when /\A\w+_provided\?\z/ then false
    end
  end
end

Instance Attribute Details

#argsObject (readonly) Also known as: to_h, to_hash

Returns the value of attribute args.



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

def args
  @args
end

Class Method Details

.aliases(*names) ⇒ Object



17
18
19
20
# File 'lib/contextuable.rb', line 17

def aliases(*names)
  @_equivalents ||= []
  @_equivalents << names.map(&:to_sym)
end

.defaults(hash) ⇒ Object



22
23
24
# File 'lib/contextuable.rb', line 22

def defaults(hash)
  @_defaults = hash
end

.ensure_presence(*names) ⇒ Object



13
14
15
# File 'lib/contextuable.rb', line 13

def ensure_presence(*names)
  @_presence_required = names.map(&:to_sym)
end

.permit(*names) ⇒ Object



26
27
28
# File 'lib/contextuable.rb', line 26

def permit(*names)
  @_permitted = names.map(&:to_sym)
end

.required(*names) ⇒ Object



9
10
11
# File 'lib/contextuable.rb', line 9

def required(*names)
  @_required = names.map(&:to_sym)
end

Instance Method Details

#[](key) ⇒ Object



44
45
46
# File 'lib/contextuable.rb', line 44

def [](key)
  args[key]
end

#[]=(key, value) ⇒ Object



48
49
50
# File 'lib/contextuable.rb', line 48

def []=(key, value)
  set_attribute(key, value)
end