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.
19 20 21 |
# File 'lib/quick_class.rb', line 19 def initialize(opts={}) opts.each { |k,v| instance_variable_set("@#{k}", v) } end |
Class Method Details
.attributes ⇒ Object
read default attributes
16 |
# File 'lib/quick_class.rb', line 16 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 |
# File 'lib/quick_class.rb', line 4 def self.attributes=(**keyvals) # if attributes is already defined, delete the attr_accessor methods @attributes&.each_key { |k| [:"#{k}", :"#{k}="].each &method(:undef_method) } # 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 |