Last active
December 14, 2015 16:49
-
-
Save 0xradical/5118270 to your computer and use it in GitHub Desktop.
Find first that matches block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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