Created
July 28, 2010 19:27
-
-
Save metaskills/495919 to your computer and use it in GitHub Desktop.
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
# Here is a neat little named scope module that let's me easily abstract out making finders based on | |
# class column names. The nice thing is that it does quite a few chores. First it makes sure that passed | |
# in column names exist in the schema. Second, it escapes values while building the string. | |
module NamedScopes | |
module AttributeScopes | |
def self.included(base) | |
base.class_eval do | |
extend ClassMethods | |
named_scope :attribute_like, lambda { |column,query| {:conditions => attribute_like_string(column,query)} } | |
named_scope :attributes_like, lambda { |query,*columns| {:conditions => attributes_like_string(query,*columns)} } | |
end | |
end | |
module ClassMethods | |
def attribute_like_string(column,query) | |
return nil if query.blank? || !self.column_names.include?(column.to_s) | |
escaped_query = self.connection.quote_string(query.strip) | |
escaped_column = self.connection.quote_column_name(column) | |
"#{escaped_column} LIKE '%#{escaped_query}%'" | |
end | |
def attributes_like_string(query,*columns) | |
columns.map do |column| | |
attribute_like_string(column,query) | |
end.compact.join(' AND ') | |
end | |
end | |
end | |
end | |
class Listing < ActiveRecord::Base | |
include NamedScopes::AttributeScopes | |
class << self | |
def find_or_create_with_attributes(attrs={}) | |
find_by_like_key_and_org_name(attrs[:address_key],attrs[:organization_legal_name]) || | |
find_by_like_key_and_contact_name(attrs[:address_key],attrs[:contact_name]) || | |
create(attrs) do |listing| | |
# Configure listing here if attrs mass assignment protects. | |
end | |
end | |
protected | |
def find_by_like_key_and_org_name(key,name) | |
return nil if [key,name].any?(&:blank) | |
attribute_like(:address_key,key).attribute_like(:organization_legal_name,name).first | |
end | |
def find_by_like_key_and_contact_name(key,name) | |
return nil if [key,name].any?(&:blank) | |
attribute_like(:address_key,key).attribute_like(:contact_name,name).first | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment