Wednesday 22 June 2016

Ruby Load Path and Auto Loading in Rails - Other small concepts





Hi Readers,

This is the last post for Ruby beginners. Today we are going to learn some small concepts and Ruby load paths and auto loading in Rails

define_method:

class Array 
  {:second => 1, :third => 2}.each do |method,element| 
    define_method(method) do 
      self[element] 
    end 
  end 
end 
 
array = %w(A B C) 
puts array.first # => A 
puts array.second # => B 
puts array.third # => C  

Object Space:

    ObjectSpace.each_object(Numeric) { |n| puts n }   

Class Reflection:

    # Using Class#superclass 
    klass = Fixnum 
    begin 
      print klass 
      klass = klass.superclass 
      print " < " if klass 
    end while klass 
    # => Fixnum < Integer < Numeric < Object 
     
    # Using Class#ancestors 
    Fixnum.ancestors 
    # => Fixnum, Integer, Precision, Numeric, Comparable, Object, Kernel 
     
    # Inspecting methods and variables 
    Fixnum.public_instance_methods(false) 
    Fixnum.class_variables 
    Fixnum.constants 
    1.instance_variables

System Hooks: Class#inherited

    class A 
      @@subclasses = {}   
      # Invoked when a new class is created that extends this class 
      def self.inherited(child) 
        puts "inherited" 
        @@subclasses[self] ||= [] 
        @@subclasses[self] << child 
      end 
       
      def self.subclasses 
        @@subclasses[self] 
      end 
    end 
     
    class B < A 
    end 
     
    puts A.subclasses   

Ruby Load Path and Auto Loading in Rails:

  • The Ruby load path is stored in $: and is used when you require code
  • Models, views, controllers, and helpers under the app dir are loaded automatically
  • Classes under lib are also loaded automatically
  • You can add load paths in config/environment.rb
  • Class and module names must correspond to the file path where they are defined for auto loading to work


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