module ClassProp::ClassMethods

Public Instance Methods

define_class_prop(prop_name, opts={}) click to toggle source

Defines the set and get methods for the given property.

option: init Sets the initial value of the property.

option: inherit If set to false, the property is not inherited by subclasses.

option: before_set If set, must be a Proc. The proc is called and val is set to the proc's return value.

# File lib/classprop.rb, line 57
def define_class_prop(prop_name, opts={})
        # default options
        opts = {'inherit'=>true}.merge(opts)
        
        # TESTING
        # $tm.show opts
        
        # set
        self.define_singleton_method("#{prop_name}=") do |val|
                # run before_set if necessary
                if before_set = opts['before_set']
                        if not before_set.is_a?(Proc)
                                raise 'before-set-not-proc'
                        end
                        
                        val = opts['before_set'].call(val)
                end
                
                # set property
                instance_variable_set "@#{prop_name}", val
        end
        
        # get
        self.define_singleton_method(prop_name) do
                if instance_variable_defined?("@#{prop_name}")
                        rv = instance_variable_get("@#{prop_name}")
                        
                        if rv == ClassProp::MustDefine
                                raise "must-define-class-property: #{prop_name}" 
                        else
                                return rv
                        end
                else
                        if opts['inherit'] and superclass.respond_to?(prop_name)
                                return superclass.public_send(prop_name)
                        else
                                return nil
                        end
                end
        end
        
        # initial value
        if opts.has_key?('init')
                instance_variable_set "@#{prop_name}", opts['init']
        end
end
delete_class_prop(prop_name) click to toggle source

delete_class_prop

# File lib/classprop.rb, line 105
def delete_class_prop(prop_name)
        if instance_variable_defined?("@#{prop_name}")
                remove_instance_variable "@#{prop_name}"
        end
end