Dynamic properties and has_key? check

2 views
Skip to first unread message

Jamie Hill

unread,
Mar 15, 2014, 8:37:08 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.
Reply all
Reply to author
Forward
0 new messages