Created
August 28, 2014 23:53
-
-
Save mipearson/a5268c277ee6bc894ff0 to your computer and use it in GitHub Desktop.
This file contains 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
# Add this to your Rails 3.2 project to add in approximations of the Rails 4 | |
# finders and disable Rails 2/3 'dynamic' finders. | |
module ActiveRecord | |
# Approximations of the new Rails 4 finders | |
class Relation | |
def take | |
first | |
end | |
def take! | |
first! | |
end | |
def find_by(*args) | |
where(*args).take | |
end | |
def find_by!(*args) | |
where(*args).take! | |
end | |
def find_or_initialize_by(attributes, &block) | |
find_by(attributes) || new(attributes, &block) | |
end | |
def find_or_create_by(attributes, &block) | |
find_by(attributes) || create(attributes, &block) | |
end | |
def find_or_create_by!(attributes, &block) | |
find_by(attributes) || create!(attributes, &block) | |
end | |
end | |
# Relation methods also need to work on our root scope | |
class Base | |
class << self | |
%w{find_by find_by! find_or_initialize_by find_or_create_by find_or_create_by!}.each do |m| | |
define_method m do |*args, &block| | |
scoped.send(m, *args, &block) | |
end | |
end | |
end | |
end | |
# Force dynamic finders to never work by overriding the magic used to match them. | |
class DynamicFinderMatch | |
def self.match(method) | |
case method.to_s | |
when /^find_(all_|last_)?by_([_a-zA-Z]\w*)$/, /^find_by_([_a-zA-Z]\w*)\!$/, /^find_or_create_by_([_a-zA-Z]\w*)\!$/, /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/ | |
ActiveSupport::Deprecation.warn("Dynamic matcher #{method} called - please remove!", caller) | |
end | |
nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment