Class: QuickClass
- Inherits:
-
Object
- Object
- QuickClass
- Defined in:
- lib/quick_class.rb
Overview
a quick and easy class factory
Class Method Summary collapse
-
.attributes ⇒ Object
read default attributes.
-
.attributes=(**keyvals) ⇒ Object
main public method - define attributes for a class.
Instance Method Summary collapse
-
#initialize(opts = {}) ⇒ QuickClass
constructor
configure attributes from #initialize.
Constructor Details
#initialize(opts = {}) ⇒ QuickClass
configure attributes from #initialize. note that defaults are not set here. Use .default for that.
21 22 23 |
# File 'lib/quick_class.rb', line 21 def initialize(opts={}) opts.each { |k,v| instance_variable_set("@#{k}", v) } end |
Class Method Details
.attributes ⇒ Object
read default attributes
18 |
# File 'lib/quick_class.rb', line 18 def self.attributes; @attributes; end |
.attributes=(**keyvals) ⇒ Object
main public method - define attributes for a class
4 5 6 7 8 9 10 11 12 13 14 15 16 |
# File 'lib/quick_class.rb', line 4 def self.attributes=(**keyvals) # if attributes is already defined, delete the attr_accessor methods @attributes&.each_key do |k| [:"#{k}", :"#{k}="].each { |m| send :undef_method, m } end # define attributes at the keyvals passed to this method as an argument, # merged with the attributes of the superclass, if there is one. @attributes = keyvals.merge(superclass&.attributes || {}) # define public attr_accessor methods for all the attributes attr_accessor *@attributes.keys # define a .default method that invokes #initialize with .attributes define_singleton_method(:default) { new @attributes } end |