Class: Hashie::Extensions::Mash::DefineAccessors::Ext

Inherits:
Module
  • Object
show all
Defined in:
lib/hashie/extensions/mash/define_accessors.rb

Instance Method Summary collapse

Constructor Details

#initializeExt

Returns a new instance of Ext.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/hashie/extensions/mash/define_accessors.rb', line 17

def initialize
  mod = self
  define_method(:method_missing) do |method_name, *args, &block|
    key, suffix = method_name_and_suffix(method_name)
    case suffix
    when '='.freeze
      mod.define_writer(key, method_name)
    when '?'.freeze
      mod.define_predicate(key, method_name)
    when '!'.freeze
      mod.define_initializing_reader(key, method_name)
    when '_'.freeze
      mod.define_underbang_reader(key, method_name)
    else
      mod.define_reader(key, method_name)
    end
    send(method_name, *args, &block)
  end
end

Instance Method Details

#define_initializing_reader(key, method_name) ⇒ Object



67
68
69
70
71
72
73
74
75
# File 'lib/hashie/extensions/mash/define_accessors.rb', line 67

def define_initializing_reader(key, method_name)
  define_method(method_name) do
    if key? method_name
      self.[](method_name, &proc)
    else
      initializing_reader(key)
    end
  end
end

#define_predicate(key, method_name) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/hashie/extensions/mash/define_accessors.rb', line 57

def define_predicate(key, method_name)
  define_method(method_name) do
    if key? method_name
      self.[](method_name, &proc)
    else
      !!self[key]
    end
  end
end

#define_reader(key, method_name) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/hashie/extensions/mash/define_accessors.rb', line 37

def define_reader(key, method_name)
  define_method(method_name) do |&block|
    if key? method_name
      self.[](method_name, &block)
    else
      self.[](key, &block)
    end
  end
end

#define_underbang_reader(key, method_name) ⇒ Object



77
78
79
80
81
82
83
84
85
# File 'lib/hashie/extensions/mash/define_accessors.rb', line 77

def define_underbang_reader(key, method_name)
  define_method(method_name) do
    if key? method_name
      self.[](key, &proc)
    else
      underbang_reader(key)
    end
  end
end

#define_writer(key, method_name) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/hashie/extensions/mash/define_accessors.rb', line 47

def define_writer(key, method_name)
  define_method(method_name) do |value = nil|
    if key? method_name
      self.[](method_name, &proc)
    else
      assign_property(key, value)
    end
  end
end