Skip to content

Instantly share code, notes, and snippets.

@0xradical
Last active December 14, 2015 16:49
Show Gist options
  • Save 0xradical/5118270 to your computer and use it in GitHub Desktop.
Save 0xradical/5118270 to your computer and use it in GitHub Desktop.
Find first that matches block
module QueryingWithBlock
def first_with(&block)
find_each do |record|
return record if block.call(record)
end
end
end
# ActiveRecord::Relation includes QueryingWithBlock
ActiveRecord::Relation.class_eval do
include QueryingWithBlock
end
# delegates in metaclass of anyone ActiveRecord::Base
# because delegate goes to any instance of the surrounding class
# the surrounding class is the metaclass which ActiveRecord::Base is an instance of...
# can also be achieved through extend
class << ActiveRecord::Base
delegate :first_with, :to => :scoped
end
User.first_with(&->(u){ u.name == 'John' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment