Dynamic properties and has_key? check.

12 views
Skip to first unread message

Jamie Hill

unread,
Mar 15, 2014, 8:35:26 PM3/15/14
to therub...@googlegroups.com
Hi,

Apologies if this is a stupid question. I would like a Ruby object to have dynamic properties based on certain conditions, am I safe to define a '[]' method and return values from there? If so, how would I return an 'undefined' value as 'nil' just translates to 'null'. I'm wondering if the code here https://github.com/cowboyd/therubyracer/blob/master/lib/v8/access/names.rb#L13-15 should perform a check first i.e:

elsif obj.respond_to?(:[]) && obj.has_key?(name) && !special?(name)

...that way I could simple override 'has_key?' as well as the '[]' method. Here is a code example of what I'm doing currently but need to know how to return 'undefined':

require 'v8'

class Proxy
  def [](name)
    # How to return undefined?
    return nil unless stuff.include?(name)
    
    define_singleton_method(name) do
      name.upcase
    end.call
  end
  
  private
  
  def stuff
    %W(foo bar)
  end
end

class Root
  def proxy
    Proxy.new
  end
end

context = V8::Context.new(with: Root.new)

puts context.eval("'foo: ' + proxy.foo + ', bar: ' + proxy.bar + ', baz: ' + proxy.baz")

Thanks in advance.

Charles Lowell

unread,
Mar 17, 2014, 9:41:48 AM3/17/14
to Jamie Hill, therub...@googlegroups.com
Jamie,

You can return undefined by yielding. This will tell your definition to not handle the call at all, and it will proceed up the prototype chain. e.g.

def [](name)
  if stuff.include? name
    # do stuff
  else
    yield
  end
end

cheers,
Charles
--
You received this message because you are subscribed to the Google Groups "The Ruby Racer" group.
To unsubscribe from this group and stop receiving emails from it, send an email to therubyracer...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages