Class: Baba::RubyObject

Inherits:
Instance show all
Defined in:
lib/baba/ruby_object.rb

Instance Method Summary collapse

Methods inherited from Instance

#inspect

Constructor Details

#initialize(klass) ⇒ RubyObject

Returns a new instance of RubyObject.



28
29
30
31
32
# File 'lib/baba/ruby_object.rb', line 28

def initialize(klass)
  super(klass)
  @methods = klass.methods.map { |m| m.to_s }
  @object = nil # By default our object is nil
end

Instance Method Details

#[](name) ⇒ Object

Raises:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/baba/ruby_object.rb', line 34

def [](name)
  klass = if @object.nil?
      @klass
    else
      @object
    end

  if name.lexeme == "new"
    method = @klass.method(name.lexeme)
    return RubyFunction.new(method, proc do |ret|
             @object = ret
             @methods = ret.methods.map { |m| m.to_s }
           end)
  end

  if name.lexeme == "array_get" # Tis is not the best idea but it works
    if @methods.include?("[]")
      method = klass.method("[]")
      return RubyFunction.new(method)
    end
  end

  if name.lexeme == "array_set"
    if @methods.include?("[]=")
      method = klass.method("[]=")
      return RubyFunction.new(method)
    end
  end

  if @methods.include?(name.lexeme)
    method = klass.method(name.lexeme)
    return RubyFunction.new(method)
  end

  raise BabaRuntimeError.new(name, "Undefined method #{name.lexeme} for #{@klass}.")
end

#[]=(name, value) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/baba/ruby_object.rb', line 71

def []=(name, value)
  klass = if @object.nil?
      @klass
    else
      @object
    end

  if @methods.include?[name.lexme + "="]
    method = klass.method(name.lexeme + "=")
    method.call(value)
  else
    raise BabaRuntimeError.new(name, "Undefined method #{name.lexme}= for #{@klass}.")
  end
end

#to_sObject



86
87
88
# File 'lib/baba/ruby_object.rb', line 86

def to_s
  "<Ruby #{@klass}: #{@object.inspect}>"
end