PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How is ruby on rails has_many (and similar) implemented?

 October 21, 2022     has-many, implementation, ruby, ruby-on-rails     No comments   

Issue

I am analysing the rails source code, because I wold like to understand the inner workings of the has_many and similar constructs.

So far, I was able to find where the method is implemented (link to github): it is in the module ActiveRecord::Associations

def has_many(name, options = {}, &extension)
  Builder::HasMany.build(self, name, options, &extension)
end

This one eventualy ends (link to github) in the class ActiveRecord::Associations::Builder::CollectionAssociation as

def self.build(model, name, options, &extension)
  new(model, name, options, &extension).build
end

There is where my ruby skills end and I could not track it further and find where is "new" implemented and what it does.

Can someone point me to the right direction and maybe comment along, what is going on under the hood?


Solution

Basically, new is defined like this:

class Class
  def new(*args, &block)
    obj = allocate

    obj.initialize(*args, &block)
    # *actually* obj.send(:initialize, *args, &block) since initialize is private

    obj
  end
end

allocate is defined like this:

class Class
  def allocate
    # magic stuff for creating an empty object which cannot be expressed in Ruby:

    new_obj = Deep::Within::VM.__somehow_magically_allocate_memory__!

    new_obj.__class__ = self

    new_obj
  end
end


Answered By - Jörg W Mittag
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing