Class: Module
- Includes:
- AntSupport::CoreExtensions::Module
- Defined in:
- lib/ant_support/core_ext/module/attribute_accessors.rb,
lib/ant_support/core_ext/module.rb,
lib/ant_support/core_ext/module/attr_accessor_with_default.rb
Overview
Extends the module object with module and instance accessors for class attributes, just like the native attr* accessors for instance attributes.
module AppConfiguration
mattr_accessor :google_api_key
self.google_api_key = "123456789"
mattr_accessor :paypal_url
self.paypal_url = "www.sandbox.paypal.com"
end
AppConfiguration.google_api_key = "overriding the api key!"
Instance Method Summary collapse
-
#attr_accessor_with_default(sym, default = nil, &block) ⇒ Object
Declare an attribute accessor with an initial default return value.
- #mattr_accessor(*syms) ⇒ Object
- #mattr_reader(*syms) ⇒ Object
- #mattr_writer(*syms) ⇒ Object
Methods included from AntSupport::CoreExtensions::Module
#alias_attribute, #alias_method_chain
Instance Method Details
#attr_accessor_with_default(sym, default = nil, &block) ⇒ Object
Declare an attribute accessor with an initial default return value.
To give attribute :age
the initial value 25
:
class Person
attr_accessor_with_default :age, 25
end
some_person.age
=> 25
some_person.age = 26
some_person.age
=> 26
To give attribute :element_name
a dynamic default value, evaluated in scope of self:
attr_accessor_with_default(:element_name) { name.underscore }
21 22 23 24 25 26 27 28 29 30 |
# File 'lib/ant_support/core_ext/module/attr_accessor_with_default.rb', line 21 def attr_accessor_with_default(sym, default = nil, &block) raise 'Default value or block required' unless !default.nil? || block define_method(sym, block_given? ? block : Proc.new { default }) module_eval(<<-EVAL, __FILE__, __LINE__) def #{sym}=(value) class << self; attr_reader :#{sym} end @#{sym} = value end EVAL end |
#mattr_accessor(*syms) ⇒ Object
54 55 56 57 |
# File 'lib/ant_support/core_ext/module/attribute_accessors.rb', line 54 def mattr_accessor(*syms) mattr_reader(*syms) mattr_writer(*syms) end |
#mattr_reader(*syms) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/ant_support/core_ext/module/attribute_accessors.rb', line 14 def mattr_reader(*syms) syms.each do |sym| next if sym.is_a?(Hash) class_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym} @@#{sym} end def #{sym} @@#{sym} end EOS end end |
#mattr_writer(*syms) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/ant_support/core_ext/module/attribute_accessors.rb', line 33 def mattr_writer(*syms) = syms. syms.each do |sym| class_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym}=(obj) @@#{sym} = obj end #{" def #{sym}=(obj) @@#{sym} = obj end " unless [:instance_writer] == false } EOS end end |