Last active
October 7, 2020 15:04
-
-
Save kwstannard/e2d9787d546dc89737190fdb200402ea to your computer and use it in GitHub Desktop.
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_generator = ->(name, attrs) { | |
file = "tmp/meta_classes/#{name.underscore}.rb" | |
FileUtils.mkdir_p(File.dirname(file)) | |
template = File.write(file, ERB.new(<<TEMP, nil, "%").result(binding)) | |
class <%= name %> | |
attr_accessor <%= attrs.map(&:inspect).join(', ') %> | |
def initialize(<%= attrs.join(", ") %>) | |
% attrs.each do |attr| | |
@<%= attr %> = <%= attr %> | |
% end | |
end | |
end | |
TEMP | |
load file | |
} | |
@class_generator.call("Foo", :key1, :key2) | |
Foo.new("hello").key1 | |
=> hello | |
show-source Foo | |
From: tmp/meta_classes/foo.rb @ line 1: | |
Class name: Foo | |
Number of lines: 8 | |
class Foo | |
attr_accessor :key1, :key2 | |
def initialize(key1, key2) | |
@key1 = key1 | |
@key2 = key2 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment