Rails: requires, class loading, and magic Paying users to use your tool
Nov 07

Feeling JavaScripty in Ruby

Ruby, Tech Add comments

I am sure there is a better way to do this, so please let me know.

It somehow came up that someone wanted to feel JavaScripty when creating objects with methods.

People often follow the pattern below in JavaScript:


{ foo: function() { ... }, bar: function() { ... } }

How about in Ruby? Lucas Carlson talked about dynamically adding methods to classes through their objects in Ruby, and of course it is simple to do:

o = Object.new
def o.foo
puts 'whee'
end

But what if you want to make this more JavaScripty:


x = {:a => lambda { puts 'whee' }, :b => lambda { puts 'foo' }}.to_o
x.a

A simple bit of code did this (without good checking of things):

class Hash
def to_o
o = Object.new
self.each do |k,v|
if v.is_a?(Proc)
o.class.instance_eval do
define_method(k.to_s, v)
end
end
end
o
end
end

Leave a Reply

Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

Q: Type in the word 'ajax'