Class: MethodFound::AttributeInterceptor
- Inherits:
-
Interceptor
- Object
- Module
- Interceptor
- MethodFound::AttributeInterceptor
- Defined in:
- lib/method_found/attribute_interceptor.rb
Overview
Class defining prefix, suffix and affix methods to a class for a given attribute name or set of attribute names.
Instance Attribute Summary
Attributes inherited from Interceptor
Instance Method Summary collapse
- #alias_attribute(new_name, old_name) ⇒ Object
- #define_attribute_methods(*attr_names) ⇒ Object
-
#initialize(prefix: '', suffix: '') ⇒ AttributeInterceptor
constructor
A new instance of AttributeInterceptor.
- #inspect ⇒ Object
- #to_proc ⇒ Object
Methods inherited from Interceptor
Constructor Details
#initialize(prefix: '', suffix: '') ⇒ AttributeInterceptor
45 46 47 48 49 50 51 52 53 |
# File 'lib/method_found/attribute_interceptor.rb', line 45 def initialize(prefix: '', suffix: '') @regex = /\A(?:#{Regexp.escape(prefix)})(.*)(?:#{Regexp.escape(suffix)})\z/ @method_missing_target = method_missing_target = "#{prefix}attribute#{suffix}" @method_name = "#{prefix}%s#{suffix}" super to_proc do |_, attr_name, *args, &block| send(method_missing_target, attr_name, *args, &block) end end |
Instance Method Details
#alias_attribute(new_name, old_name) ⇒ Object
64 65 66 67 68 69 |
# File 'lib/method_found/attribute_interceptor.rb', line 64 def alias_attribute(new_name, old_name) handler = method_name(old_name) define_method method_name(new_name) do |*arguments, &block| send(handler, *arguments, &block) end end |
#define_attribute_methods(*attr_names) ⇒ Object
55 56 57 58 59 60 61 62 |
# File 'lib/method_found/attribute_interceptor.rb', line 55 def define_attribute_methods(*attr_names) handler = @method_missing_target attr_names.each do |attr_name| define_method method_name(attr_name) do |*arguments, &block| send(handler, attr_name, *arguments, &block) end end end |
#inspect ⇒ Object
81 82 83 |
# File 'lib/method_found/attribute_interceptor.rb', line 81 def inspect "<#{self.class.name}: #{@regex.inspect}>" end |
#to_proc ⇒ Object
71 72 73 74 75 76 77 78 79 |
# File 'lib/method_found/attribute_interceptor.rb', line 71 def to_proc regex = @regex proc do |method_name| (matches = regex.match(method_name)) && (method_name != :attributes) && respond_to?(:attributes) && (attributes.keys & matches.captures).first end end |