Module: ClassProp::ClassMethods

Defined in:
lib/classprop.rb

Overview


ClassMethods

Instance Method Summary collapse

Instance Method Details

#define_class_prop(prop_name, opts = {}) ⇒ Object

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.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# 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) ⇒ Object

delete_class_prop



105
106
107
108
109
# 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