Skip to content

Instantly share code, notes, and snippets.

@johnhilts
Created October 12, 2021 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnhilts/3a48e03872b7946d5773335c4fe490ce to your computer and use it in GitHub Desktop.
Save johnhilts/3a48e03872b7946d5773335c4fe490ce to your computer and use it in GitHub Desktop.
Macro to make simple classes
(defmacro define-info-class (name &rest slots)
(labels ((make-slot (name slot)
(read-from-string
(concatenate 'string (string name) "-" (string slot)))))
(flet ((make-slot-list-item (slot)
(list slot :accessor (make-slot name slot)))
(make-name (name)
(read-from-string
(concatenate 'string (string name) "-info"))))
(let* ((class-name (make-name name))
(class-slots (mapcar #'make-slot-list-item slots)))
`(defclass ,class-name ()
,class-slots)))))
(defmacro populate-info-object (name &rest slots)
(flet ((get-setter (slot)
(let ((expression (read-from-string (concatenate 'string "((" (string name) "-" (string slot) " " (string name) ") " (string slot) ")"))))
(car `((setf ,(car expression) ,(cadr expression)))))))
(let ((object-name (read-from-string (string name)))
(setters (mapcar #'get-setter slots)))
`(progn
,@setters
,object-name))))
;; example usage
(define-info-class date second minute hour day month year day-of-the-week daylight-p zone)
(defmethod get-parsed-date ((date date-info) universal-time)
(multiple-value-bind
(second minute hour day month year day-of-the-week daylight-p zone)
(decode-universal-time universal-time)
(populate-info-object date second minute hour day month year day-of-the-week daylight-p zone)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment