Last active
January 2, 2016 22:19
-
-
Save TeknoFiend/8369045 to your computer and use it in GitHub Desktop.
Javascript "new" syntax in Ruby
This file contains 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
# Define a free function with the same name as a class (returns the class and the args passed to the function, the constructor data) | |
def javascriptenator( klass ) | |
Kernel.send( :define_method, klass.name.to_sym ) { |*args| return [klass,args] } | |
end | |
# Parameter is the return from the class-named function. Use class name to create object and pass constructor data. | |
def new( class_and_args ) | |
class_and_args.first.new( *class_and_args.last ) | |
end | |
# Now let's make a simple class | |
class Foo | |
def initialize(a,b) | |
@a,@b = a,b | |
end | |
def hello | |
puts @a, @b | |
end | |
end | |
javascriptenator(Foo) # Magic! | |
f = new Foo('Tekno','Mage') | |
f.hello |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment