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

Prying Open the Black Box

Prying Open the Black Box

Every once a while, Rails might behave in strange ways that you did not expect, and it could be difficult to figure out what is really going on. Was it a bug in the framework? Could it be one of the gems I am using? Did I do something wrong?

In this session, we will look at some tips, tricks and tools to help you debug your Rails issues. Along the way, you will also learn how to dive into the Rails codebase without getting lost. The next time you a mysterious bug finds its way into your Rails applications, you will be well-equipped to pry open the black box yourself!

Godfrey Chan

April 21, 2015
Tweet

More Decks by Godfrey Chan

Other Decks in Programming

Transcript

  1. Ƅ

  2. I have a very particular set of skills, skills I

    have acquired over a very long career. Skills that make me a nightmare for bugs like you. I will look for you, I will find you, and I will fix you. What I Think I Do
  3. Rails has no magic folks, it has sane defaults and

    conventions, take a "magical" feeling as "I need to grok the docs on this" Xavier Noria @fxn
  4. @fxn it feels like magic because even before you grok

    it, it still works. The cost of learning is not piled on up front. Sebastian Delmont @sd
  5. NoMethodError NameError TypeError WrongEncodingError ArgumentError Circular dependency detected while autoloading

    consta veRecord::StatementInvalid Redis::CannotConn RangeError ActiveRecord::Subclas JSON::ParserError Dalli::RingErro SystemStackEr ActiveJob::DeserializationErro RuntimeError
  6. 1. You wrote some code 2. You ran the code

    3. You expected something to happen
  7. 1. You wrote some code 2. You ran the code

    3. You expected something to happen 4. That didn’t happen
  8. 1. You wrote the code 2. You ran the code

    3. You expected something to happen 4. That didn’t happen
  9. 1. You wrote the code 2. You have access to

    the code 3. You expected something to happen 4. That didn’t happen
  10. 1. You wrote the code 2. You have access to

    the code 3. You know what went wrong 4. That didn’t happen
  11. 1. You wrote the code 2. You have access to

    the code 3. You know what went wrong 4. Your bug is not going anywhere
  12. PostsController (block in #create) Post#ensure_author User#ensure_permission PostsController#create app/models/user.rb:3:in `ensure_permission' app/models/post.rb:5:in

    `ensure_author' app/controllers/posts_controller.rb:30:in `block in create' app/controllers/posts_controller.rb:29:in `create'
  13. PostsController (block in #create) Post#ensure_author User#ensure_permission PostsController#create class PostsController <

    ... def create @post = Post.new(post_params) respond_to do |format| if @post.save ... end end end end
  14. PostsController (block in #create) Post#ensure_author User#ensure_permission PostsController#create class PostsController <

    ... def create @post = Post.new(post_params) respond_to do |format| if @post.save ... end end end end
  15. PostsController (block in #create) Post#ensure_author User#ensure_permission PostsController#create class Post <

    ActiveRecord::Base belongs_to :author, class_name: "User" before_save :ensure_author def ensure_author author.ensure_permission(:authorship) end end
  16. PostsController (block in #create) Post#ensure_author User#ensure_permission PostsController#create class User <

    ActiveRecord::Base has_many :permissions has_many :posts def ensure_permission(role) permissions.find_by_type!(role) end end
  17. PostsController (block in #create) Post#ensure_author User#ensure_permission PostsController#create ActiveRecord::SubclassNotFound (The single-table

    inheritance...): app/models/user.rb:3:in `ensure_permission' app/models/post.rb:5:in `ensure_author' app/controllers/posts_controller.rb:30:in `block in create' app/controllers/posts_controller.rb:29:in `create'
  18. app/models/user.rb:3:in `ensure_permission' app/models/post.rb:5:in `ensure_author' ? ? ? ? ? ?

    ? ? ? ? app/controllers/posts_controller.rb:30:in `block in create' app/controllers/posts_controller.rb:29:in `create' ? ? ? ? ? ? ? ? ? ?
  19. # Be sure to restart your server when you modify

    this file. # You can add backtrace silencers for libraries that you're # using but don't wish to see in your backtraces. # # Rails.backtrace_cleaner.add_silencer do |line| # line =~ /my_noisy_library/ # end # You can also remove all the silencers if you're trying to # debug a problem that might stem from framework code. # # Rails.backtrace_cleaner.remove_silencers! config/initializers/backtrace_silencers.rb
  20. # Be sure to restart your server when you modify

    this file. # You can add backtrace silencers for libraries that you're # using but don't wish to see in your backtraces. # # Rails.backtrace_cleaner.add_silencer do |line| # line =~ /my_noisy_library/ # end # You can also remove all the silencers if you're trying to # debug a problem that might stem from framework code. Rails.backtrace_cleaner.remove_silencers! config/initializers/backtrace_silencers.rb
  21. ActiveRecord::SubclassNotFound (The single-table inheritance...): /rails/activerecord/lib/active_record/inheritance.rb:176:in `rescue in find_sti_class' /rails/activerecord/lib/active_record/inheritance.rb:170:in `find_sti_class'

    /rails/activerecord/lib/active_record/inheritance.rb:159:in `discriminate_class_for_record' /rails/activerecord/lib/active_record/persistence.rb:67:in `instantiate' /rails/activerecord/lib/active_record/querying.rb:50:in `block (2 levels) in find_by_sql' /rails/activerecord/lib/active_record/result.rb:51:in `block in each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/querying.rb:50:in `map' /rails/activerecord/lib/active_record/querying.rb:50:in `block in find_by_sql' /rails/activesupport/lib/active_support/notifications/instrumenter.rb:20:in `instrument' /rails/activerecord/lib/active_record/querying.rb:49:in `find_by_sql' /rails/activerecord/lib/active_record/statement_cache.rb:107:in `execute'
  22. ActiveRecord::SubclassNotFound (The single-table inheritance...): /rails/activerecord/lib/active_record/inheritance.rb:176:in `rescue in find_sti_class' /rails/activerecord/lib/active_record/inheritance.rb:170:in `find_sti_class'

    /rails/activerecord/lib/active_record/inheritance.rb:159:in `discriminate_class_for_record' /rails/activerecord/lib/active_record/persistence.rb:67:in `instantiate' /rails/activerecord/lib/active_record/querying.rb:50:in `block (2 levels) in find_by_sql' /rails/activerecord/lib/active_record/result.rb:51:in `block in each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/querying.rb:50:in `map' /rails/activerecord/lib/active_record/querying.rb:50:in `block in find_by_sql' /rails/activesupport/lib/active_support/notifications/instrumenter.rb:20:in `instrument' /rails/activerecord/lib/active_record/querying.rb:49:in `find_by_sql' /rails/activerecord/lib/active_record/statement_cache.rb:107:in `execute' /rails/activerecord/lib/active_record/core.rb:192:in `find_by' /rails/activerecord/lib/active_record/dynamic_matchers.rb:65:in `find_by_type_and_user_id' /rails/activerecord/lib/active_record/dynamic_matchers.rb:19:in `method_missing' app/models/user.rb:3:in `ensure_permission' app/models/post.rb:5:in `ensure_author' /rails/activesupport/lib/active_support/callbacks.rb:428:in `block in make_lambda' /rails/activesupport/lib/active_support/callbacks.rb:164:in `call' /rails/activesupport/lib/active_support/callbacks.rb:164:in `block (2 levels) in halting' /rails/activesupport/lib/active_support/callbacks.rb:599:in `call' /rails/activesupport/lib/active_support/callbacks.rb:599:in `block (2 levels) in default_terminator' /rails/activesupport/lib/active_support/callbacks.rb:598:in `catch' /rails/activesupport/lib/active_support/callbacks.rb:598:in `block in default_terminator' /rails/activesupport/lib/active_support/callbacks.rb:165:in `call' /rails/activesupport/lib/active_support/callbacks.rb:165:in `block in halting' /rails/activesupport/lib/active_support/callbacks.rb:500:in `call' /rails/activesupport/lib/active_support/callbacks.rb:500:in `block in call' /rails/activesupport/lib/active_support/callbacks.rb:500:in `each' /rails/activesupport/lib/active_support/callbacks.rb:500:in `call' /rails/activesupport/lib/active_support/callbacks.rb:90:in `run_callbacks' /rails/activerecord/lib/active_record/callbacks.rb:301:in `create_or_update' /rails/activerecord/lib/active_record/persistence.rb:151:in `save!' /rails/activerecord/lib/active_record/validations.rb:43:in `save!' /rails/activerecord/lib/active_record/attribute_methods/dirty.rb:29:in `save!' /rails/activerecord/lib/active_record/transactions.rb:303:in `block in save!' /rails/activerecord/lib/active_record/transactions.rb:374:in `block in with_transaction_returning_status' /rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `block in transaction' /rails/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb:183:in `within_new_transaction' /rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `transaction' /rails/activerecord/lib/active_record/transactions.rb:210:in `transaction' /rails/activerecord/lib/active_record/transactions.rb:371:in `with_transaction_returning_status' /rails/activerecord/lib/active_record/transactions.rb:303:in `save!' /rails/activerecord/lib/active_record/suppressor.rb:42:in `save!' app/controllers/posts_controller.rb:30:in `block in create' /rails/actionpack/lib/action_controller/metal/mime_responds.rb:190:in `respond_to' app/controllers/posts_controller.rb:29:in `create' /rails/actionpack/lib/action_controller/metal/implicit_render.rb:4:in `send_action' /rails/actionpack/lib/abstract_controller/base.rb:189:in `process_action' /rails/actionpack/lib/action_controller/metal/rendering.rb:21:in `process_action' /rails/actionpack/lib/abstract_controller/callbacks.rb:20:in `block in process_action' /rails/activesupport/lib/active_support/callbacks.rb:117:in `call' /rails/activesupport/lib/active_support/callbacks.rb:117:in `call' /rails/activesupport/lib/active_support/callbacks.rb:558:in `block (2 levels) in compile' /rails/activesupport/lib/active_support/callbacks.rb:501:in `call' /rails/activesupport/lib/active_support/callbacks.rb:501:in `call' /rails/activesupport/lib/active_support/callbacks.rb:90:in `run_callbacks' /rails/actionpack/lib/abstract_controller/callbacks.rb:19:in `process_action' /rails/actionpack/lib/action_controller/metal/rescue.rb:29:in `process_action' /rails/actionpack/lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' /rails/activesupport/lib/active_support/notifications.rb:164:in `block in instrument' /rails/activesupport/lib/active_support/notifications/instrumenter.rb:20:in `instrument' /rails/activesupport/lib/active_support/notifications.rb:164:in `instrument' /rails/actionpack/lib/action_controller/metal/instrumentation.rb:30:in `process_action' /rails/actionpack/lib/action_controller/metal/params_wrapper.rb:249:in `process_action' /rails/activerecord/lib/active_record/railties/controller_runtime.rb:18:in `process_action' /rails/actionpack/lib/abstract_controller/base.rb:128:in `process' /rails/actionview/lib/action_view/rendering.rb:30:in `process' /rails/actionpack/lib/action_controller/metal.rb:194:in `dispatch' /rails/actionpack/lib/action_controller/metal.rb:241:in `block in action' /rails/actionpack/lib/action_dispatch/routing/route_set.rb:73:in `call' /rails/actionpack/lib/action_dispatch/routing/route_set.rb:73:in `dispatch' /rails/actionpack/lib/action_dispatch/routing/route_set.rb:42:in `serve' /rails/actionpack/lib/action_dispatch/journey/router.rb:43:in `block in serve' /rails/actionpack/lib/action_dispatch/journey/router.rb:30:in `each' /rails/actionpack/lib/action_dispatch/journey/router.rb:30:in `serve' /rails/actionpack/lib/action_dispatch/routing/route_set.rb:769:in `call' rack (1.6.0) lib/rack/etag.rb:24:in `call' rack (1.6.0) lib/rack/conditionalget.rb:38:in `call' rack (1.6.0) lib/rack/head.rb:13:in `call' /rails/actionpack/lib/action_dispatch/middleware/params_parser.rb:27:in `call' /rails/actionpack/lib/action_dispatch/middleware/flash.rb:266:in `call' rack (1.6.0) lib/rack/session/abstract/id.rb:225:in `context' rack (1.6.0) lib/rack/session/abstract/id.rb:220:in `call' /rails/actionpack/lib/action_dispatch/middleware/cookies.rb:560:in `call' /rails/activerecord/lib/active_record/query_cache.rb:36:in `call' /rails/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb:642:in `call' /rails/activerecord/lib/active_record/migration.rb:378:in `call' /rails/actionpack/lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' /rails/activesupport/lib/active_support/callbacks.rb:86:in `run_callbacks' /rails/actionpack/lib/action_dispatch/middleware/callbacks.rb:27:in `call' /rails/actionpack/lib/action_dispatch/middleware/reloader.rb:73:in `call' /rails/actionpack/lib/action_dispatch/middleware/remote_ip.rb:78:in `call' /rails/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb:47:in `call' /Users/godfrey/.rvm/gems/ruby-2.2.2/bundler/gems/web-console-f5255e303d66/lib/web_console/middleware.rb:37:in `call' /rails/actionpack/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' /rails/railties/lib/rails/rack/logger.rb:38:in `call_app' /rails/railties/lib/rails/rack/logger.rb:20:in `block in call' /rails/activesupport/lib/active_support/tagged_logging.rb:70:in `block in tagged' /rails/activesupport/lib/active_support/tagged_logging.rb:26:in `tagged' /rails/activesupport/lib/active_support/tagged_logging.rb:70:in `tagged' /rails/railties/lib/rails/rack/logger.rb:20:in `call' /rails/actionpack/lib/action_dispatch/middleware/request_id.rb:25:in `call' rack (1.6.0) lib/rack/methodoverride.rb:22:in `call' rack (1.6.0) lib/rack/runtime.rb:18:in `call' /rails/activesupport/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' rack (1.6.0) lib/rack/lock.rb:17:in `call' /rails/actionpack/lib/action_dispatch/middleware/static.rb:115:in `call' rack (1.6.0) lib/rack/sendfile.rb:113:in `call' /rails/railties/lib/rails/engine.rb:518:in `call' /rails/railties/lib/rails/application.rb:165:in `call' rack (1.6.0) lib/rack/lock.rb:17:in `call' rack (1.6.0) lib/rack/content_length.rb:15:in `call' rack (1.6.0) lib/rack/handler/webrick.rb:89:in `service' /Users/godfrey/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service' /Users/godfrey/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run' /Users/godfrey/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'
  23. ActiveRecord::SubclassNotFound (The single-table inheritance...): /rails/activerecord/lib/active_record/inheritance.rb:176:in `rescue in find_sti_class' /rails/activerecord/lib/active_record/inheritance.rb:170:in `find_sti_class'

    /rails/activerecord/lib/active_record/inheritance.rb:159:in `discriminate_class_for_record' /rails/activerecord/lib/active_record/persistence.rb:67:in `instantiate' /rails/activerecord/lib/active_record/querying.rb:50:in `block (2 levels) in find_by_sql' /rails/activerecord/lib/active_record/result.rb:51:in `block in each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/querying.rb:50:in `map' /rails/activerecord/lib/active_record/querying.rb:50:in `block in find_by_sql' /rails/activesupport/lib/active_support/notifications/instrumenter.rb:20:in `instrument' /rails/activerecord/lib/active_record/querying.rb:49:in `find_by_sql' /rails/activerecord/lib/active_record/statement_cache.rb:107:in `execute' /rails/activerecord/lib/active_record/core.rb:192:in `find_by' /rails/activerecord/lib/active_record/dynamic_matchers.rb:65:in `find_by_type_and_user_id' /rails/activerecord/lib/active_record/dynamic_matchers.rb:19:in `method_missing' app/models/user.rb:3:in `ensure_permission' app/models/post.rb:5:in `ensure_author' /rails/activesupport/lib/active_support/callbacks.rb:428:in `block in make_lambda' /rails/activesupport/lib/active_support/callbacks.rb:164:in `call' /rails/activesupport/lib/active_support/callbacks.rb:164:in `block (2 levels) in halting' /rails/activesupport/lib/active_support/callbacks.rb:599:in `call' /rails/activesupport/lib/active_support/callbacks.rb:599:in `block (2 levels) in default_terminator' /rails/activesupport/lib/active_support/callbacks.rb:598:in `catch' /rails/activesupport/lib/active_support/callbacks.rb:598:in `block in default_terminator' /rails/activesupport/lib/active_support/callbacks.rb:165:in `call' /rails/activesupport/lib/active_support/callbacks.rb:165:in `block in halting' /rails/activesupport/lib/active_support/callbacks.rb:500:in `call' /rails/activesupport/lib/active_support/callbacks.rb:500:in `block in call' /rails/activesupport/lib/active_support/callbacks.rb:500:in `each' /rails/activesupport/lib/active_support/callbacks.rb:500:in `call' /rails/activesupport/lib/active_support/callbacks.rb:90:in `run_callbacks' /rails/activerecord/lib/active_record/callbacks.rb:301:in `create_or_update' /rails/activerecord/lib/active_record/persistence.rb:151:in `save!' /rails/activerecord/lib/active_record/validations.rb:43:in `save!' /rails/activerecord/lib/active_record/attribute_methods/dirty.rb:29:in `save!' /rails/activerecord/lib/active_record/transactions.rb:303:in `block in save!' /rails/activerecord/lib/active_record/transactions.rb:374:in `block in with_transaction_returning_status' /rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `block in transaction' /rails/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb:183:in `within_new_transaction' /rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `transaction' /rails/activerecord/lib/active_record/transactions.rb:210:in `transaction' /rails/activerecord/lib/active_record/transactions.rb:371:in `with_transaction_returning_status' /rails/activerecord/lib/active_record/transactions.rb:303:in `save!' /rails/activerecord/lib/active_record/suppressor.rb:42:in `save!' app/controllers/posts_controller.rb:30:in `block in create' /rails/actionpack/lib/action_controller/metal/mime_responds.rb:190:in `respond_to' app/controllers/posts_controller.rb:29:in `create' /rails/actionpack/lib/action_controller/metal/implicit_render.rb:4:in `send_action' /rails/actionpack/lib/abstract_controller/base.rb:189:in `process_action' /rails/actionpack/lib/action_controller/metal/rendering.rb:21:in `process_action' /rails/actionpack/lib/abstract_controller/callbacks.rb:20:in `block in process_action' /rails/activesupport/lib/active_support/callbacks.rb:117:in `call' /rails/activesupport/lib/active_support/callbacks.rb:117:in `call' /rails/activesupport/lib/active_support/callbacks.rb:558:in `block (2 levels) in compile' /rails/activesupport/lib/active_support/callbacks.rb:501:in `call' /rails/activesupport/lib/active_support/callbacks.rb:501:in `call' /rails/activesupport/lib/active_support/callbacks.rb:90:in `run_callbacks' /rails/actionpack/lib/abstract_controller/callbacks.rb:19:in `process_action' /rails/actionpack/lib/action_controller/metal/rescue.rb:29:in `process_action' /rails/actionpack/lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' /rails/activesupport/lib/active_support/notifications.rb:164:in `block in instrument' /rails/activesupport/lib/active_support/notifications/instrumenter.rb:20:in `instrument' /rails/activesupport/lib/active_support/notifications.rb:164:in `instrument' /rails/actionpack/lib/action_controller/metal/instrumentation.rb:30:in `process_action' /rails/actionpack/lib/action_controller/metal/params_wrapper.rb:249:in `process_action' /rails/activerecord/lib/active_record/railties/controller_runtime.rb:18:in `process_action' /rails/actionpack/lib/abstract_controller/base.rb:128:in `process' /rails/actionview/lib/action_view/rendering.rb:30:in `process' /rails/actionpack/lib/action_controller/metal.rb:194:in `dispatch' /rails/actionpack/lib/action_controller/metal.rb:241:in `block in action' /rails/actionpack/lib/action_dispatch/routing/route_set.rb:73:in `call' /rails/actionpack/lib/action_dispatch/routing/route_set.rb:73:in `dispatch' /rails/actionpack/lib/action_dispatch/routing/route_set.rb:42:in `serve' /rails/actionpack/lib/action_dispatch/journey/router.rb:43:in `block in serve' /rails/actionpack/lib/action_dispatch/journey/router.rb:30:in `each' /rails/actionpack/lib/action_dispatch/journey/router.rb:30:in `serve' /rails/actionpack/lib/action_dispatch/routing/route_set.rb:769:in `call' rack (1.6.0) lib/rack/etag.rb:24:in `call' rack (1.6.0) lib/rack/conditionalget.rb:38:in `call' rack (1.6.0) lib/rack/head.rb:13:in `call' /rails/actionpack/lib/action_dispatch/middleware/params_parser.rb:27:in `call' /rails/actionpack/lib/action_dispatch/middleware/flash.rb:266:in `call' rack (1.6.0) lib/rack/session/abstract/id.rb:225:in `context' rack (1.6.0) lib/rack/session/abstract/id.rb:220:in `call' /rails/actionpack/lib/action_dispatch/middleware/cookies.rb:560:in `call' /rails/activerecord/lib/active_record/query_cache.rb:36:in `call' /rails/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb:642:in `call' /rails/activerecord/lib/active_record/migration.rb:378:in `call' /rails/actionpack/lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' /rails/activesupport/lib/active_support/callbacks.rb:86:in `run_callbacks' /rails/actionpack/lib/action_dispatch/middleware/callbacks.rb:27:in `call' /rails/actionpack/lib/action_dispatch/middleware/reloader.rb:73:in `call' /rails/actionpack/lib/action_dispatch/middleware/remote_ip.rb:78:in `call' /rails/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb:47:in `call' /Users/godfrey/.rvm/gems/ruby-2.2.2/bundler/gems/web-console-f5255e303d66/lib/web_console/middleware.rb:37:in `call' /rails/actionpack/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' /rails/railties/lib/rails/rack/logger.rb:38:in `call_app' /rails/railties/lib/rails/rack/logger.rb:20:in `block in call' /rails/activesupport/lib/active_support/tagged_logging.rb:70:in `block in tagged' /rails/activesupport/lib/active_support/tagged_logging.rb:26:in `tagged' /rails/activesupport/lib/active_support/tagged_logging.rb:70:in `tagged' /rails/railties/lib/rails/rack/logger.rb:20:in `call' /rails/actionpack/lib/action_dispatch/middleware/request_id.rb:25:in `call' rack (1.6.0) lib/rack/methodoverride.rb:22:in `call' rack (1.6.0) lib/rack/runtime.rb:18:in `call' /rails/activesupport/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' rack (1.6.0) lib/rack/lock.rb:17:in `call' /rails/actionpack/lib/action_dispatch/middleware/static.rb:115:in `call' rack (1.6.0) lib/rack/sendfile.rb:113:in `call' /rails/railties/lib/rails/engine.rb:518:in `call' /rails/railties/lib/rails/application.rb:165:in `call' rack (1.6.0) lib/rack/lock.rb:17:in `call' rack (1.6.0) lib/rack/content_length.rb:15:in `call' rack (1.6.0) lib/rack/handler/webrick.rb:89:in `service' /Users/godfrey/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service' /Users/godfrey/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run' /Users/godfrey/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread' /rails/activerecord/lib/active_record/querying.rb:49:in `find_by_sql' /rails/activerecord/lib/active_record/statement_cache.rb:107:in `execute' /rails/activerecord/lib/active_record/core.rb:192:in `find_by' /rails/activerecord/lib/active_record/dynamic_matchers.rb:65:in `find_by_type_and_user_id' /rails/activerecord/lib/active_record/dynamic_matchers.rb:19:in `method_missing' app/models/user.rb:3:in `ensure_permission' app/models/post.rb:5:in `ensure_author' /rails/activesupport/lib/active_support/callbacks.rb:428:in `block in make_lambda' /rails/activesupport/lib/active_support/callbacks.rb:164:in `call' /rails/activesupport/lib/active_support/callbacks.rb:164:in `block (2 levels) in halting' /rails/activesupport/lib/active_support/callbacks.rb:599:in `call' /rails/activesupport/lib/active_support/callbacks.rb:599:in `block (2 levels) in default_terminator' /rails/activesupport/lib/active_support/callbacks.rb:598:in `catch' /rails/activesupport/lib/active_support/callbacks.rb:598:in `block in default_terminator' /rails/activesupport/lib/active_support/callbacks.rb:165:in `call' /rails/activesupport/lib/active_support/callbacks.rb:165:in `block in halting' /rails/activesupport/lib/active_support/callbacks.rb:500:in `call' /rails/activesupport/lib/active_support/callbacks.rb:500:in `block in call' /rails/activesupport/lib/active_support/callbacks.rb:500:in `each' /rails/activesupport/lib/active_support/callbacks.rb:500:in `call' /rails/activesupport/lib/active_support/callbacks.rb:90:in `run_callbacks' /rails/activerecord/lib/active_record/callbacks.rb:301:in `create_or_update' /rails/activerecord/lib/active_record/persistence.rb:151:in `save!' /rails/activerecord/lib/active_record/validations.rb:43:in `save!' /rails/activerecord/lib/active_record/attribute_methods/dirty.rb:29:in `save!' /rails/activerecord/lib/active_record/transactions.rb:303:in `block in save!' /rails/activerecord/lib/active_record/transactions.rb:374:in `block in with_transaction_returning_status' /rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `block in transaction' /rails/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb:183:in `within_new_transaction' /rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:211:in `transaction' /rails/activerecord/lib/active_record/transactions.rb:210:in `transaction' /rails/activerecord/lib/active_record/transactions.rb:371:in `with_transaction_returning_status' /rails/activerecord/lib/active_record/transactions.rb:303:in `save!' /rails/activerecord/lib/active_record/suppressor.rb:42:in `save!' app/controllers/posts_controller.rb:30:in `block in create' /rails/actionpack/lib/action_controller/metal/mime_responds.rb:190:in `respond_to' app/controllers/posts_controller.rb:29:in `create' /rails/actionpack/lib/action_controller/metal/implicit_render.rb:4:in `send_action' /rails/actionpack/lib/abstract_controller/base.rb:189:in `process_action' /rails/actionpack/lib/action_controller/metal/rendering.rb:21:in `process_action'
  24. class User < ActiveRecord::Base has_many :permissions has_many :posts def ensure_permission(role)

    raise "lolwut, how did I get here??" permissions.find_by_type!(role) end end
  25. class ApplicationController < ActionController::Base def current_user require "pp" puts "ZOMG

    " * 1000 puts puts "Stack Trace:" puts caller puts puts "User ID: #{ session[:user_id].inspect }" puts puts "User:" pp User.find_by_id(session[:user_id]) puts puts "LOL " * 1000 @current_user ||= User.find_by_id(session[:user_id]) end end
  26. group :development, :test do # Call 'byebug' anywhere in the

    code to stop execution # and get a debugger console gem 'byebug' # Access an IRB console on exception pages or by using # <%= console %> in views gem 'web-console' ... end Gemfile
  27. Started GET "/posts/1" for ::1 at 2015-04-20 14:22:58 -0400 Processing

    by PostsController#show as HTML Parameters: {"id"=>"1"} [1, 9] in /private/tmp/demo/app/controllers/application_controller.rb 1: class ApplicationController < ActionController::Base 2: 3: def current_user 4: byebug 5: => 6: @current_user ||= User.find_by_id(session[:user_id]) 7: end 8: 9: end (byebug)
  28. ActiveRecord::SubclassNotFound (The single-table inheritance...): /rails/activerecord/lib/active_record/inheritance.rb:176:in `rescue in find_sti_class' /rails/activerecord/lib/active_record/inheritance.rb:170:in `find_sti_class'

    /rails/activerecord/lib/active_record/inheritance.rb:159:in `discriminate_class_for_record' /rails/activerecord/lib/active_record/persistence.rb:67:in `instantiate' /rails/activerecord/lib/active_record/querying.rb:50:in `block (2 levels) in find_by_sql' /rails/activerecord/lib/active_record/result.rb:51:in `block in each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/querying.rb:50:in `map' /rails/activerecord/lib/active_record/querying.rb:50:in `block in find_by_sql' /rails/activesupport/lib/active_support/notifications/instrumenter.rb:20:in `instrument' /rails/activerecord/lib/active_record/querying.rb:49:in `find_by_sql' /rails/activerecord/lib/active_record/statement_cache.rb:107:in `execute'
  29. ActiveRecord::SubclassNotFound (The single-table inheritance...): /rails/activerecord/lib/active_record/inheritance.rb:176:in `rescue in find_sti_class' /rails/activerecord/lib/active_record/inheritance.rb:170:in `find_sti_class'

    /rails/activerecord/lib/active_record/inheritance.rb:159:in `discriminate_class_for_record' /rails/activerecord/lib/active_record/persistence.rb:67:in `instantiate' /rails/activerecord/lib/active_record/querying.rb:50:in `block (2 levels) in find_by_sql' /rails/activerecord/lib/active_record/result.rb:51:in `block in each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/querying.rb:50:in `map' /rails/activerecord/lib/active_record/querying.rb:50:in `block in find_by_sql' /rails/activesupport/lib/active_support/notifications/instrumenter.rb:20:in `instrument' /rails/activerecord/lib/active_record/querying.rb:49:in `find_by_sql' /rails/activerecord/lib/active_record/statement_cache.rb:107:in `execute'
  30. ActiveRecord::SubclassNotFound (The single-table inheritance...): /rails/activerecord/lib/active_record/inheritance.rb:176:in `rescue in find_sti_class' /rails/activerecord/lib/active_record/inheritance.rb:170:in `find_sti_class'

    /rails/activerecord/lib/active_record/inheritance.rb:159:in `discriminate_class_for_record' /rails/activerecord/lib/active_record/persistence.rb:67:in `instantiate' /rails/activerecord/lib/active_record/querying.rb:50:in `block (2 levels) in find_by_sql' /rails/activerecord/lib/active_record/result.rb:51:in `block in each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/result.rb:51:in `each' /rails/activerecord/lib/active_record/querying.rb:50:in `map' /rails/activerecord/lib/active_record/querying.rb:50:in `block in find_by_sql' /rails/activesupport/lib/active_support/notifications/instrumenter.rb:20:in `instrument' /rails/activerecord/lib/active_record/querying.rb:49:in `find_by_sql' /rails/activerecord/lib/active_record/statement_cache.rb:107:in `execute'
  31. require 'active_support/core_ext/hash/indifferent_access' module ActiveRecord # == Single table inheritance #

    # Active Record allows inheritance by storing the name of the class in a column that by # default is named "type" (can be changed by overwriting <tt>Base.inheritance_column</tt>). # This means that an inheritance looking like this: # # class Company < ActiveRecord::Base; end # class Firm < Company; end # class Client < Company; end # class PriorityClient < Client; end # # When you do <tt>Firm.create(name: "37signals")</tt>, this record will be saved in # the companies table with type = "Firm". You can then fetch this row again using # <tt>Company.where(name: '37signals').first</tt> and it will return a Firm object. # # Be aware that because the type column is an attribute on the record every new # subclass will instantly be marked as dirty and the type column will be included # in the list of changed attributes on the record. This is different from non # STI classes: # # Company.new.changed? # => false # Firm.new.changed? # => true # Firm.new.changes # => {"type"=>["","Firm"]} # # If you don't have a type column defined in your table, single-table inheritance won't # be triggered. In that case, it'll work just like normal subclasses with no special magic # for differentiating between them or reloading the right type with find. # # Note, all the attributes for all the cases are kept in the same table. Read more: # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html # module Inheritance extend ActiveSupport::Concern included do # Determines whether to store the full constant name including namespace when using STI. class_attribute :store_full_sti_class, instance_writer: false self.store_full_sti_class = true end module ClassMethods # Determines if one of the attributes passed in is the inheritance column, # and if the inheritance column is attr accessible, it initializes an # instance of the given subclass instead of the base class. def new(*args, &block) if abstract_class? || self == Base raise NotImplementedError, "#{self} is an abstract class and cannot be instantiated." end attrs = args.first if subclass_from_attributes?(attrs) subclass = subclass_from_attributes(attrs) end if subclass subclass.new(*args, &block) else super end end # Returns +true+ if this does not need STI type condition. Returns # +false+ if STI type condition needs to be applied. def descends_from_active_record? if self == Base false elsif superclass.abstract_class? superclass.descends_from_active_record? else superclass == Base || !columns_hash.include?(inheritance_column) end end def finder_needs_type_condition? #:nodoc: # This is like this because benchmarking justifies the strange :false stuff :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) end # Returns the class descending directly from ActiveRecord::Base, or # an abstract class, if any, in the inheritance hierarchy. # # If A extends AR::Base, A.base_class will return A. If B descends from A # through some arbitrarily deep hierarchy, B.base_class will return A. # # If B < A and C < B and if A is an abstract_class then both B.base_class # and C.base_class would return B as the answer since A is an abstract_class. def base_class unless self < Base raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord" end if superclass == Base || superclass.abstract_class? self else superclass.base_class end end # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>). # If you are using inheritance with ActiveRecord and don't want child classes # to utilize the implied STI table name of the parent class, this will need to be true. # For example, given the following: # # class SuperClass < ActiveRecord::Base # self.abstract_class = true # end # class Child < SuperClass # self.table_name = 'the_table_i_really_want' # end # # # <tt>self.abstract_class = true</tt> is required to make <tt>Child<.find,.create, or any Arel method></tt> use <tt>the_table_i_really_want</tt> instead of a table called <tt>super_classes</tt> # attr_accessor :abstract_class # Returns whether this class is an abstract class or not. def abstract_class? defined?(@abstract_class) && @abstract_class == true end def sti_name store_full_sti_class ? name : name.demodulize end protected # Returns the class type of the record using the current module as a prefix. So descendants of # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. def compute_type(type_name) if type_name.match(/^::/) # If the type is prefixed with a scope operator then we assume that # the type_name is an absolute reference. ActiveSupport::Dependencies.constantize(type_name) else # Build a list of candidates to search for candidates = [] name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } candidates << type_name candidates.each do |candidate| constant = ActiveSupport::Dependencies.safe_constantize(candidate) return constant if candidate == constant.to_s end raise NameError.new("uninitialized constant #{candidates.first}", candidates.first) end end private # Called by +instantiate+ to decide which class to use for a new # record instance. For single-table inheritance, we check the record # for a +type+ column and return the corresponding class. def discriminate_class_for_record(record) if using_single_table_inheritance?(record) find_sti_class(record[inheritance_column]) else super end end def using_single_table_inheritance?(record) record[inheritance_column].present? && columns_hash.include?(inheritance_column) end def find_sti_class(type_name) if store_full_sti_class ActiveSupport::Dependencies.constantize(type_name) else compute_type(type_name) end rescue NameError raise SubclassNotFound, "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " + "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " + "Please rename this column if you didn't intend it to be used for storing the inheritance class " + "or overwrite #{name}.inheritance_column to use another column for that information." end def type_condition(table = arel_table) sti_column = table[inheritance_column] sti_names = ([self] + descendants).map(&:sti_name) sti_column.in(sti_names) end # Detect the subclass from the inheritance column of attrs. If the inheritance column value # is not self or a valid subclass, raises ActiveRecord::SubclassNotFound # If this is a StrongParameters hash, and access to inheritance_column is not permitted, # this will ignore the inheritance column and return nil def subclass_from_attributes?(attrs) attribute_names.include?(inheritance_column) && attrs.is_a?(Hash) end def subclass_from_attributes(attrs) subclass_name = attrs.with_indifferent_access[inheritance_column] if subclass_name.present? && subclass_name != self.name subclass = subclass_name.safe_constantize unless descendants.include?(subclass) raise ActiveRecord::SubclassNotFound.new("Invalid single-table inheritance type: #{subclass_name} is not a subclass of #{name}") end subclass end end end def initialize_dup(other) super ensure_proper_type end private def initialize_internals_callback super ensure_proper_type end # Sets the attribute used for single table inheritance to this class name if this is not the # ActiveRecord::Base descendant. # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to # do Reply.new without having to set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself. # No such attribute would be set for objects of the Message class in that example. def ensure_proper_type klass = self.class if klass.finder_needs_type_condition? write_attribute(klass.inheritance_column, klass.sti_name) end end end end
  32. 1. What does this method do? 2. What are the

    inputs? 3. What is expected to happen?
  33. 1. What does this method do? 2. What are the

    inputs? 3. What is expected to happen? 4. Did that happen?
  34. module ActiveRecord module Inheritance module ClassMethods def find_sti_class(type_name) if store_full_sti_class

    ActiveSupport::Dependencies.constantize(type_name) else compute_type(type_name) end rescue NameError raise SubclassNotFound, "The single-table inheritance mechanism..." end end end end
  35. module ActiveRecord module Inheritance module ClassMethods def find_sti_class(type_name) if store_full_sti_class

    ActiveSupport::Dependencies.constantize(type_name) else compute_type(type_name) end rescue NameError raise SubclassNotFound, "The single-table inheritance mechanism..." end end end end
  36. module ActiveRecord module Inheritance module ClassMethods def find_sti_class(type_name) if store_full_sti_class

    ActiveSupport::Dependencies.constantize(type_name) else compute_type(type_name) end rescue NameError raise SubclassNotFound, "The single-table inheritance mechanism..." end end end end
  37. module ActiveRecord module Inheritance module ClassMethods def find_sti_class(type_name) if store_full_sti_class

    ActiveSupport::Dependencies.constantize(type_name) else compute_type(type_name) end rescue NameError raise SubclassNotFound, "The single-table inheritance mechanism..." end end end end
  38. module ActiveRecord module Inheritance module ClassMethods def find_sti_class(type_name) if store_full_sti_class

    ActiveSupport::Dependencies.constantize(type_name) else compute_type(type_name) end rescue NameError raise SubclassNotFound, "The single-table inheritance mechanism..." end end end end
  39. module ActiveRecord module Inheritance module ClassMethods def find_sti_class(type_name) if store_full_sti_class

    ActiveSupport::Dependencies.constantize(type_name) else compute_type(type_name) end rescue NameError raise SubclassNotFound, "The single-table inheritance mechanism..." end end end end Where is this defined?
  40. module ActiveRecord module Inheritance module ClassMethods def find_sti_class(type_name) if store_full_sti_class

    ActiveSupport::Dependencies.constantize(type_name) else byebug compute_type(type_name) end rescue NameError raise SubclassNotFound, "The single-table inheritance mechanism..." end end end end
  41. # Returns the class type of the record using the

    current module as a prefix. So descendants of # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. def compute_type(type_name) if type_name.match(/^::/) # If the type is prefixed with a scope operator then we assume that # the type_name is an absolute reference. ActiveSupport::Dependencies.constantize(type_name) else # Build a list of candidates to search for candidates = [] name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } candidates << type_name candidates.each do |candidate| constant = ActiveSupport::Dependencies.safe_constantize(candidate) return constant if candidate == constant.to_s end raise NameError.new("uninitialized constant #{candidates.first}", candidates.first) end end
  42. # Returns the class type of the record using the

    current module as a prefix. So descendants of # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. def compute_type(type_name) if type_name.match(/^::/) # If the type is prefixed with a scope operator then we assume that # the type_name is an absolute reference. ActiveSupport::Dependencies.constantize(type_name) else # Build a list of candidates to search for candidates = [] name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } candidates << type_name candidates.each do |candidate| constant = ActiveSupport::Dependencies.safe_constantize(candidate) return constant if candidate == constant.to_s end raise NameError.new("uninitialized constant #{candidates.first}", candidates.first) end end
  43. # Returns the class type of the record using the

    current module as a prefix. So descendants of # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. def compute_type(type_name) if type_name.match(/^::/) # If the type is prefixed with a scope operator then we assume that # the type_name is an absolute reference. ActiveSupport::Dependencies.constantize(type_name) else # Build a list of candidates to search for candidates = [] name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } candidates << type_name candidates.each do |candidate| constant = ActiveSupport::Dependencies.safe_constantize(candidate) return constant if candidate == constant.to_s end raise NameError.new("uninitialized constant #{candidates.first}", candidates.first) end end
  44. ceb33f84 (Jon Leighton # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. ceb33f84

    (Jon Leighton def compute_type(type_name) ceb33f84 (Jon Leighton if type_name.match(/^::/) ceb33f84 (Jon Leighton # If the type is prefixed with a scope operator then we assume that ceb33f84 (Jon Leighton # the type_name is an absolute reference. ceb33f84 (Jon Leighton ActiveSupport::Dependencies.constantize(type_name) ceb33f84 (Jon Leighton else ceb33f84 (Jon Leighton # Build a list of candidates to search for ceb33f84 (Jon Leighton candidates = [] ceb33f84 (Jon Leighton name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } ceb33f84 (Jon Leighton candidates << type_name ceb33f84 (Jon Leighton ceb33f84 (Jon Leighton candidates.each do |candidate| c965de39 (Arthur Neves constant = ActiveSupport::Dependencies.safe_constantize(candidate) c965de39 (Arthur Neves return constant if candidate == constant.to_s ceb33f84 (Jon Leighton end ceb33f84 (Jon Leighton bea44cba (Chulki Lee raise NameError.new("uninitialized constant #{candidates.first}", candidates.first) ceb33f84 (Jon Leighton end ceb33f84 (Jon Leighton end
  45. ceb33f8 Split out most of the AR::Base code into separate

    modules :cake: (Jon Leighton, 3 years, 4 months ago) diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index 92f3666..de73715 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -39,6 +39,7 @@ module ActiveRecord autoload :Aggregations autoload :Associations autoload :AttributeMethods + autoload :AttributeAssignment autoload :AutosaveAssociation autoload :Relation @@ -57,27 +58,37 @@ module ActiveRecord autoload :Base autoload :Callbacks autoload :CounterCache + autoload :DefaultScope + autoload :DynamicMatchers autoload :DynamicFinderMatch autoload :DynamicScopeMatch + autoload :Explain + autoload :IdentityMap + autoload :Inheritance + autoload :Integration