Hi Readers,
Today we are going to learn that if any class is not defined, even though you are trying to create object for that non existing class, then ruby raises an exception called "constant_missing".
a = 2
eval code, binding
end
a = 1
evaluate_code("puts a", binding) # => 1
Today we are going to learn that if any class is not defined, even though you are trying to create object for that non existing class, then ruby raises an exception called "constant_missing".
const_missing – for Auto Loading Classes:
def Object.const_missing(name)
@looked_for ||= {}
str_name = name.to_s
raise "Class not found: #{name}" if @looked_for[str_name]
@looked_for[str_name] = 1
file = str_name.downcase
require file
klass = const_get(name)
return klass if klass
raise "Class not found: #{name}"
end
@looked_for ||= {}
str_name = name.to_s
raise "Class not found: #{name}" if @looked_for[str_name]
@looked_for[str_name] = 1
file = str_name.downcase
require file
klass = const_get(name)
return klass if klass
raise "Class not found: #{name}"
end
eval and binding:
def evaluate_code(code, binding)a = 2
eval code, binding
end
a = 1
evaluate_code("puts a", binding) # => 1
instance_eval:
require 'person_class'
andreas = Person.new("Andreas")
puts andreas.instance_eval { @name } # => Andreas
class_eval and module_eval:
class Person
def self.add_method(method)
class_eval %Q{
def #{method}
puts "method #{method} invoked"
end
}
end
add_method(:say_hi)
end
Person.new.say_hi
def self.add_method(method)
class_eval %Q{
def #{method}
puts "method #{method} invoked"
end
}
end
add_method(:say_hi)
end
Person.new.say_hi
Thank for reading it, hope you will practice and get some idea.
No comments:
Post a Comment