Permalink
Browse files

support for 2 dimensional arrays and ordered hashes

  • Loading branch information...
1 parent 0cee417 commit 5854a6fa91c045d14fb205aa3556fb12ad8e77bd Aditya Sanghi committed Sep 27, 2010
Showing with 27 additions and 5 deletions.
  1. +16 −5 lib/enumlogic.rb
  2. +10 −0 spec/enumlogic_spec.rb
  3. +1 −0 spec/spec_helper.rb
View
@@ -1,4 +1,5 @@
require "active_record"
+require "active_support"
# See the enum class level method for more info.
module Enumlogic
@@ -7,6 +8,7 @@ module Enumlogic
# class Computer < ActiveRecord::Base
# enum :kind, ["apple", "dell", "hp"]
# enum :kind, {"apple" => "Apple", "dell" => "Dell", "hp" => "HP"}
+ # enum :kind, [["apple", "Apple"], ["dell", "Dell"], ["hp", "HP"]]
# end
#
# You can now do the following:
@@ -21,20 +23,29 @@ module Enumlogic
# c.kind_text # "apple" or "Apple" if you gave a hash with a user friendly text value
# c.enum?(:kind) # true
def enum(field, values, options = {})
+ values_array = []
values_hash = if values.is_a?(Array)
- hash = {}
- values.each { |value| hash[value] = value }
+ hash = ActiveSupport::OrderedHash.new
+ values.each do |value|
+ # Handle 2 dimensional arrays
+ if value.is_a?(Array)
+ hash[value[0]] = value[1]
+ values_array.push(value[1])
+ else
+ hash[value] = value
+ values_array.push(value)
+ end
+ end
hash
else
+ values_array = values.keys
values
end
- values_array = values.is_a?(Hash) ? values.keys : values
-
constant_name = options[:constant] || field.to_s.pluralize.upcase
const_set constant_name, values_array unless const_defined?(constant_name)
- new_hash = {}
+ new_hash = ActiveSupport::OrderedHash.new
values_hash.each do |key,text|
new_hash[text] = key
end
View
@@ -26,6 +26,11 @@
Computer.kind_options.should == {"Apple" => "apple", "Dell" => "dell", "HP" => "hp"}
end
+ it "should create class level options method for 2 dimensional arrays" do
+ Computer.enum :kind, [["apple", "Apple"], ["dell", "Dell"], ["hp", "HP"]]
+ Computer.kind_options.should == {"Apple" => "apple", "Dell" => "dell", "HP" => "hp"}
+ end
+
it "should create key methods" do
Computer.enum :kind, ["apple", "dell", "hp"]
c = Computer.new(:kind => "apple")
@@ -38,6 +43,11 @@
c.kind_key.should == :apple
end
+ it "should create ordered hash for arrays" do
+ Computer.enum :kind, ["apple", "dell", "hp"]
+ Computer.kind_options.keys.should == ["apple", "dell", "hp"]
+ end
+
it "should create text methods" do
Computer.enum :kind, {"apple" => "Apple", "dell" => "Dell", "hp" => "HP"}
c = Computer.new(:kind => "hp")
View
@@ -4,6 +4,7 @@
require 'spec/autorun'
require 'rubygems'
require 'active_record'
+require 'active_support'
require "#{File.dirname(__FILE__)}/../init"
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")

0 comments on commit 5854a6f

Please sign in to comment.