Skip to content

Instantly share code, notes, and snippets.

@kwstannard
Last active October 7, 2020 15:04
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 kwstannard/e2d9787d546dc89737190fdb200402ea to your computer and use it in GitHub Desktop.
Save kwstannard/e2d9787d546dc89737190fdb200402ea to your computer and use it in GitHub Desktop.
@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