Module: Amp::ModuleExtensions
- Included in:
- Plugins::Base
- Defined in:
- lib/amp-front/support/module_extensions.rb
Overview
These are extensions to Amp modules. This module should be extended by any Amp modules seeking to take advantage of them. This prevents conflicts with other libraries defining extensions of the same name.
Instance Method Summary collapse
-
#cattr_accessor(*attrs) ⇒ Object
Creates readers and writers for the given instance variables.
- #cattr_accessor_with_default(attr, default) ⇒ Object
-
#cattr_get_and_setter(*attrs) ⇒ Object
Creates a DSL-friendly set-and-getter method.
-
#cattr_reader(*attrs) ⇒ Object
Creates a reader for the given instance variables on the class object.
-
#cattr_writer(*attrs) ⇒ Object
Creates a writer for the given instance variables on the class object.
- #singleton_class ⇒ Object
Instance Method Details
#cattr_accessor(*attrs) ⇒ Object
Creates readers and writers for the given instance variables.
41 42 43 44 |
# File 'lib/amp-front/support/module_extensions.rb', line 41 def cattr_accessor(*attrs) cattr_reader(*attrs) cattr_writer(*attrs) end |
#cattr_accessor_with_default(attr, default) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/amp-front/support/module_extensions.rb', line 46 def cattr_accessor_with_default(attr, default) varname = "@#{attr}".to_sym singleton_class.instance_eval do define_method attr do if instance_variable_defined?(varname) instance_variable_get(varname) else instance_variable_set(varname, default) default end end end cattr_writer(attr) end |
#cattr_get_and_setter(*attrs) ⇒ Object
Creates a DSL-friendly set-and-getter method. The method, when called with no arguments, acts as a getter. When called with arguments, it acts as a setter. Uses class instance variables - this is not for generating instance methods.
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/amp-front/support/module_extensions.rb', line 74 def cattr_get_and_setter(*attrs) attrs.each do |attr| cattr_accessor attr singleton_class.instance_eval do alias_method "#{attr}_old_get".to_sym, attr define_method attr do |*args, &blk| if args.size > 0 send("#{attr}=", *args) elsif blk != nil send("#{attr}=", blk) else send("#{attr}_old_get") end end end end end |
#cattr_reader(*attrs) ⇒ Object
Creates a reader for the given instance variables on the class object.
27 28 29 30 31 |
# File 'lib/amp-front/support/module_extensions.rb', line 27 def cattr_reader(*attrs) attrs.each do |attr| instance_eval("def #{attr}; @#{attr}; end") end end |
#cattr_writer(*attrs) ⇒ Object
Creates a writer for the given instance variables on the class object.
34 35 36 37 38 |
# File 'lib/amp-front/support/module_extensions.rb', line 34 def cattr_writer(*attrs) attrs.each do |attr| instance_eval("def #{attr}=(val); @#{attr} = val; end") end end |
#singleton_class ⇒ Object
20 21 22 23 24 |
# File 'lib/amp-front/support/module_extensions.rb', line 20 def singleton_class class << self self end end |