Skip to content

Instantly share code, notes, and snippets.

@TeknoFiend
Last active January 2, 2016 22:19
Show Gist options
  • Save TeknoFiend/8369045 to your computer and use it in GitHub Desktop.
Save TeknoFiend/8369045 to your computer and use it in GitHub Desktop.
Javascript "new" syntax in Ruby
# 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