Class: MethodObject
- Inherits:
-
Object
- Object
- MethodObject
- Defined in:
- lib/method_object.rb,
lib/method_object/version.rb,
lib/method_object/parameter.rb
Overview
Allows for the creation of method objects, to ease the extraction of complex methods from other classes and the implementation of service objects.
A method object works similarly to a proc/lambda, exposing a MethodObject.call method and convenience MethodObject.to_proc method to convert it to a Proc.
Major differences in behaviour compared to a ‘lambda`:
* It accepts only named parameters
* It performs type checking on the parameters
Constant Summary collapse
- VERSION =
"0.1.0"
Class Method Summary collapse
-
.call(**args) ⇒ Object
Calls the MethodObject with the given arguments.
-
.to_proc ⇒ Proc
Returns a proc that calls the MO with the given arguments.
Instance Method Summary collapse
-
#call ⇒ Object
Calls the method object with the parameters currently set.
-
#initialize(**args) ⇒ MethodObject
constructor
A new instance of MethodObject.
-
#parameters ⇒ Hash{Symbol => Object}
Returns a hash with the parameters currently set.
-
#to_proc ⇒ Proc
Returns a lambda that calls the method object with the parameters currently set.
Constructor Details
#initialize(**args) ⇒ MethodObject
Returns a new instance of MethodObject.
138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/method_object.rb', line 138 def initialize(**args) self.class.send(:parameters).freeze @monitor = Monitor.new args.each { |k, v| public_send("#{k}=", v) } self.class.send(:parameters) .reject { |p| args.keys.map(&:to_sym).include?(p.name) } .select(&:default?) .each { |p| public_send("#{p.name}=", p.default_in(self)) } end |
Class Method Details
.call(**args) ⇒ Object
Calls the MethodObject with the given arguments.
68 69 70 |
# File 'lib/method_object.rb', line 68 def call(**args) new(**args).call end |
.to_proc ⇒ Proc
Returns a proc that calls the MO with the given arguments.
74 75 76 |
# File 'lib/method_object.rb', line 74 def to_proc proc { |**args| call(**args) } end |
Instance Method Details
#call ⇒ Object
Calls the method object with the parameters currently set.
163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/method_object.rb', line 163 def call unless respond_to?(:do_call, true) raise NotImplementedError, 'Implementation missing. Please use `called { ... }` to define method body' end @monitor.synchronize do assert_required_arguments! do_call end end |
#parameters ⇒ Hash{Symbol => Object}
Returns a hash with the parameters currently set.
152 153 154 155 156 157 158 |
# File 'lib/method_object.rb', line 152 def parameters Hash[ self.class.send(:parameters).map(&:name) .select { |p| instance_variable_defined?("@#{p}") } .map { |p| [p, public_send(p)] } ] end |
#to_proc ⇒ Proc
Returns a lambda that calls the method object with the parameters currently set.
177 178 179 |
# File 'lib/method_object.rb', line 177 def to_proc -> { call } end |