Module: ClassAttributes
- Extended by:
- ClassAttributes
- Included in:
- ClassAttributes
- Defined in:
- lib/common/class_attributes.rb
Overview
User.current = User.first
Constant Summary collapse
- CA_DEFAULTS =
{}
Instance Method Summary collapse
-
#define(klass, name, default = nil, &block) ⇒ Object
defines class variable.
Instance Method Details
#define(klass, name, default = nil, &block) ⇒ Object
defines class variable
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/common/class_attributes.rb', line 31 def define klass, name, default=nil, &block raise ArgumentError, 'name must be symbol' unless name.class == Symbol default ||= block if block ::ClassAttributes::CA_DEFAULTS[name] = { 'Object'=>default } klass.define_singleton_method('%s=' % name) { |*args| send name, *args} klass.define_singleton_method(name) do |*args| root = ::ClassAttributes::CA_DEFAULTS[name] # set and return if argument defined return root[to_s] = args[0] if args.length > 0 # find value and return ancestors.map(&:to_s).each do |el| value = root[el] if value || el == 'Object' value = instance_exec(&value) if value.is_a?(Proc) return value end end end end |