App Academy - w3d5
Today was our second solo project and we got to build our own version of ActiveRecord! Pretty cool... especially since we got to use meta-programming to make classes dynamic enough to represent varying tables from a database. In other words, for any class that inherited from our version of 'ActiveRecord', we could automatically determined the corresponding table based on the class name and provided methods that could convert the table data into objects (and vice verse) as well as add or update the data. We were also able to support 'belongs_to', 'has_many' and 'has_one_through' associations!
Meta-programming (and Reflection)
Ruby is supports reflection (a.k.a. introspection)... the ability for a program to examine itself.
'send' allows us to call functions dynamically
'define_method' allows us to define methods dynamically
'method_missing' is a method called for all methods that do not exist and can respond according to how you define this method. (allows for infinite functions... like 'find_by_...')
'class' and '.is_a?' are methods used to find class information for an object. With this we can handle method arguments of varying types
Class Instance Variables
Classes can also have instance variables. However, these instance variables aren't inherited. Instead a new class instance is created
Classes can also have class variables which are shared between super-class and subclass
Global variables are prefixed with '$' and are accessible anywhere because the live outside of any class
Global variables should be avoided since they aren't very object oriented
Random cool things I learned...
uniqueness can't be enforced with 'create_table'. 'add_index' is used instead.
'bundle' and 'bundle install' does the same thing since 'install' is the default option for 'bundle'
you can 'constantize' (or 'Object.const_get) a string to create a class object
'class' scope vs 'instance' scope... (thanks, Jeff!)
source: https://thenewcircle.com/static/bookshelf/ruby_tutorial/scope.html










