Skip to content

Commit

Permalink
Allow a different column to be specified as the key column
Browse files Browse the repository at this point in the history
  • Loading branch information
jhubert committed Feb 13, 2012
1 parent 3fe25e1 commit 1cb2651
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 5 deletions.
13 changes: 10 additions & 3 deletions lib/acts_as_keyed/class_methods.rb
Expand Up @@ -5,23 +5,30 @@ def acts_as_keyed(options={})
class_attribute :options

options[:as_param] ||= false
options[:column] ||= 'key'
options[:size] ||= 10
options[:chars] ||= ('a'..'z').to_a + ('A'..'Z').to_a + (1..9).to_a - ['l','I','O']

self.options = options

raise MissingKeyColumnError if ActiveRecord::Base.connection.table_exists?(self.table_name) && columns_hash['key'].nil?
options[:column] = options[:column].to_s

attr_protected :key
raise MissingKeyColumnError if ActiveRecord::Base.connection.table_exists?(self.table_name) && columns_hash[options[:column]].nil?

attr_protected options[:column]

class << self
def find(*args)
if self.options[:as_param] && args.first.is_a?(String)
find_by_key(args)
send("find_by_#{options[:column]}", args)
else
super(*args)
end
end

def key_exists?(k)
exists?(["#{options[:column]} = ?", k])
end
end

include InstanceMethods
Expand Down
10 changes: 9 additions & 1 deletion lib/acts_as_keyed/instance_methods.rb
Expand Up @@ -10,13 +10,21 @@ def regenerate_key!
self.save
end

def key=(val)
write_attribute(options[:column], val)
end

def key
read_attribute(options[:column])
end

protected

def create_key
k = nil
100.times do
k = random_key
break if self.class.count(:conditions => { :key => k }) == 0
break if !self.class.key_exists?(k)
k = nil
end
raise NoAvailableKeysError if k.nil?
Expand Down
2 changes: 1 addition & 1 deletion lib/acts_as_keyed/version.rb
@@ -1,3 +1,3 @@
module ActsAsKeyed
VERSION = "0.1.1"
VERSION = "0.1.2"
end
14 changes: 14 additions & 0 deletions test/acts_as_keyed_test.rb
Expand Up @@ -60,6 +60,20 @@ class ActsAsKeyedTest < ActsAsKeyedBaseTest
end
end

test "should use a different column if specified as a string" do
ObjectWithoutKey.acts_as_keyed(:column => 'name')

o = ObjectWithoutKey.create()
assert_not_nil o.name
end

test "should use a different column if specified as a symbol" do
ObjectWithoutKey.acts_as_keyed(:column => :name)

o = ObjectWithoutKey.create()
assert_not_nil o.name
end

test "should fail if object doesn't have key column" do
output = nil

Expand Down

0 comments on commit 1cb2651

Please sign in to comment.