Skip to content

Instantly share code, notes, and snippets.

@nixpulvis
Last active December 14, 2015 19:59
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 nixpulvis/5140741 to your computer and use it in GitHub Desktop.
Save nixpulvis/5140741 to your computer and use it in GitHub Desktop.
Generate ruby classes from text files.
data = File.read('classes.txt')
classes = data.split(/^$\n/)
classes.each do |klass|
name, *methods = klass.split(/:?\n/)
Object.const_set(name, Class.new do
methods.each do |method|
parse = method.match(/(?<name>\w+) \(?(?<arguments>[\w\, ]*)\)? ?-> {(?<body>.*)}/)
if parse[:arguments].empty?
define_method(parse[:name]) { eval parse[:body] }
else
arguments = parse[:arguments].split(', ')
define_method(parse[:name]) do |*args|
eigenclass = class << self; self; end
arguments.each_with_index do |arg, i|
eigenclass.class_eval { attr_accessor arg }
eval "self.#{arg} = :#{args[i]}"
end
eval parse[:body]
end
end
end
end)
end
Foo:
math -> { 1 + 3 }
strings (a, b) -> { "#{a} and #{b}" }
Bar:
google -> { `curl www.google.com` }
funny -> { google.gsub("Lucky", "Funny") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment