Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rediscovering ActiveRecord

Rediscovering ActiveRecord

Being a Rails developer is more than just understanding how to use the Framework to develop applications.

To become an efficient developer, you should learn how the Framework works; how deep this understanding should be is up to you. Exploring the Framework code is something that everyone should do at least once.

Not only may you learn how it works but also, you might learn new tricks from the code itself or discover small features that are not widely publicized.

Mario Alberto Chávez

May 04, 2016
Tweet

More Decks by Mario Alberto Chávez

Other Decks in Programming

Transcript

  1. michelada.io # activerecord/lib/active_record/ connection_adapters/schema_cache.rb # Get the columns for a

    table def columns(table_name) @columns[table_name] ||= connection.columns(table_name) end
  2. michelada.io # lib/active_record/statement_cache.rb 
 def self.create(connection, block = Proc.new) relation

    = block.call Params.new bind_map = BindMap.new( relation.bound_attributes) query_builder = connection.cacheable_query( relation.arel) new query_builder, bind_map end
  3. michelada.io relation = block.call Params.new Arel::Node::Equality ActiveRecord::Relation:: QueryAttribute Arel::Nodes::BindParam ID


    ActiveRecord::Statement Cache::Substitute Arel::Attributes::Attribute
 ID Where clause
  4. michelada.io # lib/active_record/statement_cache.rb def execute(params, klass, connection) bind_values = bind_map.bind

    params sql = query_builder.sql_for( bind_values, connection) klass.find_by_sql( sql, bind_values, preparable: true) end
  5. michelada.io klass.find_by_sql(sql, bind_values, preparable: true) result_set = connection.select_all(sanitize_sql(sql), 
 "#{name}

    Load”, binds, preparable: preparable) result_set.map { |record| instantiate(record, column_types) }
  6. michelada.io def init_with(coder) coder = LegacyYamlAdapter.convert( self.class, coder) @attributes =

    coder['attributes'] init_internals @new_record = coder['new_record'] self.class.define_attribute_methods _run_find_callbacks _run_initialize_callbacks self end
  7. michelada.io What we have learned? •There is no magic in

    ActiveRecord •It caches and is lazy as much as possible •Following the code is not hard