Tuesday 14 June 2016

const_missing – for Auto Loading Classes, eval and binding

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".

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  

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   


Thank for reading it, hope you will practice and get some idea.




No comments:

Post a Comment

My Experience in RUBYCONF INDIA 2016

Hi Readers, Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 ma...