Skip to content

Commit

Permalink
add readme and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rubysolo committed May 27, 2009
1 parent 64833f4 commit 2bb559f
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 4 deletions.
31 changes: 31 additions & 0 deletions README
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
= finder

http://github.com/rubysolo/finder

== DESCRIPTION:

finder is a super light rails plugin that adds hash-style lookups to ActiveRecord models

== EXAMPLE:

Given the following class definition:

class State < ActiveRecord::Base
finder :abbreviation
end

You can look up states via their abbreviations like so:

@colorado = State[:co]

This is roughly equivalent to the following implementation:

class State < ActiveRecord::Base
validates_uniqueness_of :abbreviation

def self.[](state_code)
find_by_abbreviation(state_code)
end
end

...except it adds ActiveSupport caching for speedy lookups.
2 changes: 1 addition & 1 deletion init.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require 'finder'
ActiveRecord::Base.class_eval do
include ActiveRecord::Finder
include Rubysolo::Finder
end
15 changes: 12 additions & 3 deletions lib/finder.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
module ActiveRecord # :nodoc:
require 'activesupport' unless defined? ActiveSupport
require 'activerecord' unless defined? ActiveRecord

module Rubysolo # :nodoc:
module Finder
def self.included(base) # :nodoc:
base.extend ClassMethods
Expand All @@ -11,16 +14,18 @@ class << self
end
self.finder_attribute = attr_name

self.send(:include, Finder)
self.send(:include, FindableModel)
(class << self; self; end).module_eval do
alias_method "for_#{attr_name}".to_sym, :[]
end
end
end

module Finder
module FindableModel
def self.included(base)
base.instance_eval do
validates_uniqueness_of finder_attribute

cattr_accessor :cache_store
self.cache_store = ActiveSupport::Cache::MemoryStore.new

Expand All @@ -29,6 +34,10 @@ def self.[](token)
end
end
end

def is?(token)
self[self.class.finder_attribute] == token.to_s
end
end
end
end

0 comments on commit 2bb559f

Please sign in to comment.