Skip to content

Instantly share code, notes, and snippets.

@xaviervia
Last active December 12, 2015 02:48
Show Gist options
  • Save xaviervia/4701127 to your computer and use it in GitHub Desktop.
Save xaviervia/4701127 to your computer and use it in GitHub Desktop.
Fast way to create a class dynamically and add methods to it.
# Creating the class
class_reference = Object.const_set 'Shalalala', Class.new(Array) # Array will be setted as the superclass for Shalalala. Neat, ha?
# defining a method
class_reference.class_eval do
define_method :my_method, proc { puts 'hello' }
end
# See for yourself
instance = class_reference.new
instance.my_method # => 'hello'
# Most interestingly, the class was defined in the constant so can be referenced anywhere
Shalalala.new.my_method # => 'hello'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment