Module: Hippo::Concerns::AttrAccessorWithDefault::ClassMethods

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

Instance Method Summary collapse

Instance Method Details

#attr_accessor_with_default(name, default = nil) ⇒ 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) (defaults to: nil)

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



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

def attr_accessor_with_default( name, default=nil )
    attr_writer name
    attr_add_default_setting_method(name)
    attr_reader_with_default(name, default)
end

#attr_add_default_setting_method(name) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/hippo/concerns/attr_accessor_with_default.rb', line 37

def attr_add_default_setting_method(name)
    module_eval do
        define_singleton_method(name) do |value = nil|
            attr_reader_with_default(name, value) if value
            instance_variable_get("@#{name}".to_sym)
        end
    end
end

#attr_reader_with_default(name, default) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/hippo/concerns/attr_accessor_with_default.rb', line 46

def attr_reader_with_default( name, default )
    instance_var = "@#{name.to_s}".to_sym
    instance_variable_set(instance_var, default)
    module_eval do
        define_method(name) do
            class << self; self; end.class_eval do
                attr_reader(name)
            end
            if instance_variable_defined?(instance_var)
                instance_variable_get(instance_var)
            else
                instance_variable_set(instance_var,
                                      default.is_a?(Proc) ?
                                          instance_exec(&default) : default )
            end
        end
    end
end