Module: Skr::Concerns::AttrAccessorWithDefault::ClassMethods

Defined in:
lib/skr/concerns/attr_accessor_with_default.rb

Instance Method Summary collapse

Instance Method Details

#attr_accessor_with_default(name, default) ⇒ Object

defines a attr_accessor with a default value

Examples:


Shared = Struct.new(:str)
class AttrTestClass
    include AttrAccessorWithDefault
    attr_accessor_with_default :non_copying, ->{ Shared.new("a default string") }
    attr_accessor_with_default :shared, Shared.new("a default string")
end
a = AttrTestClass.new
b = AttrTestClass.new
a.non_copying.str                   #=> "a default string"
a.non_copying.str  = "new_string"   #=> "new string"
b.non_copying.str                   #=> "a default string"

a.shared.str                   #=> "a default string"
b.shared.str                   #=> "a default string"
a.shared.str = "new string"    #=> "new string"
b.shared.str                   #=> "new string"

Parameters:

  • name (Symbol)

    name of the attribute

  • default (Object, lambda, Proc)

    if a value is given, be aware that it will be shared between instances



31
32
33
34
# File 'lib/skr/concerns/attr_accessor_with_default.rb', line 31

def attr_accessor_with_default( name, default )
    attr_writer name
    attr_reader_with_default( name, default )
end

#attr_reader_with_default(name, default) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/skr/concerns/attr_accessor_with_default.rb', line 36

def attr_reader_with_default( name, default )
    module_eval do
        define_method( name ) do
            class << self; self; end.class_eval do
                attr_reader( name )
            end
            if instance_variables.include? "@#{name}"
                instance_variable_get( "@#{name}" )
            else
                instance_variable_set( "@#{name}", default.is_a?(Proc) ? default.call : default )
            end
        end
    end
end