Skip to content

Instantly share code, notes, and snippets.

@mipearson
Created August 28, 2014 23:53
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 mipearson/a5268c277ee6bc894ff0 to your computer and use it in GitHub Desktop.
Save mipearson/a5268c277ee6bc894ff0 to your computer and use it in GitHub Desktop.
# 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