Last active
August 29, 2018 07:43
-
-
Save avdi/6123055 to your computer and use it in GitHub Desktop.
Modules for macros. In reference to: http://thepugautomatic.com/2013/07/dsom/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SomeORM | |
def self.attributes(*names) | |
if const_defined?(:DynamicAttributes, false) | |
mod = const_get(:DynamicAttributes) | |
else | |
mod = const_set(:DynamicAttributes, Module.new) | |
include mod | |
end | |
mod.module_eval do | |
names.each do |name| | |
define_method(name) do | |
# Stuff | |
end | |
end | |
end | |
end | |
end |
I checked out episode 28, it's in there. Clever!
For my own future reference, the above could be achieved with something along the lines of (after line 15):
def mod.to_s
"DynamicAttributes(#{instance_methods(false).join(', ')})"
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I also like to define a custom
#to_s
on these modules so that when listed with#ancestors
you see e.g.DynamicAttributes(attr1, attr2, attr3)
. I think I showed that in one of the RubyTapas episodes I mentioned on Twitter.