Skip to content

Instantly share code, notes, and snippets.

@nuclearsandwich
Created September 9, 2011 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuclearsandwich/1207107 to your computer and use it in GitHub Desktop.
Save nuclearsandwich/1207107 to your computer and use it in GitHub Desktop.
ActiveRecord's untraceable monkey patch on Enumerable#find(*args)
# A has_many relation exists between a Twitter account and mentions.
# An instance of the collection of mentions is of class Array, rather than any kind of ActiveRecord relation. So one would assume that standard Enumerable methods work. But...
pry(Api)> cd Account::Twitter.last
pry(#<Api::Account::Twitter:0x10748de58>):1> mentions.class
=> Array < Object # Regular old array.
pry(#<Api::Account::Twitter:0x10748de58>):1> mentions.method :find
=> Array (Enumerable)#find(*arg1) # Looks like #find was defined in Enumerable and so should be Enumerable's find (hint: It isn't)
pry(#<Api::Account::Twitter:0x10748de58>):1> mentions.find { true } # This should return the first element in the Array.
ActiveRecord::RecordNotFound: Couldn't find Aji::Mention without an ID
from /Users/steven/.rvm/gems/ruby-1.9.2-p290@api/gems/activerecord-3.0.10/lib/active_record/relation/finder_methods.rb:287:in `find_with_ids'
# What the heck?
# At the very least couldn't you tag the patch with a module so we can see that it won't behave as we expect?
# I get why this is bad and all since you don't want to be pulling a ton of records out of the database just to return one, but in
# this case I have the small collection of objects I am looking at in memory already and want to find one of them for use.
# In the meantime I am using #detect which is an alias for find that hasn't been patched over.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment