From dde11ed5c8b409c09e045cb38a40cc67314c6740 Mon Sep 17 00:00:00 2001 From: Alexandre Klein Date: Thu, 5 Jul 2012 15:22:29 +0900 Subject: [PATCH 1/2] add 'localise' option to translate labels --- .../attribute/attribute_descriptor.rb | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/lib/enumerated_attribute/attribute/attribute_descriptor.rb b/lib/enumerated_attribute/attribute/attribute_descriptor.rb index 3ea330c..d98ab86 100644 --- a/lib/enumerated_attribute/attribute/attribute_descriptor.rb +++ b/lib/enumerated_attribute/attribute/attribute_descriptor.rb @@ -9,7 +9,11 @@ def initialize(name, enums=[], opts={}) super enums @name = name @options = opts - @labels_hash = Hash[*self.collect{|e| [e, e.to_s.gsub(/_/, ' ').squeeze(' ').capitalize]}.flatten] + if @options.key?(:localize) && @options[:localize] + @labels_hash = Hash[*self.collect{|e| [e, e.to_s]}.flatten] + else + @labels_hash = Hash[*self.collect{|e| [e, e.to_s.gsub(/_/, ' ').squeeze(' ').capitalize]}.flatten] + end end def allows_nil? @@ -23,18 +27,25 @@ def enums self end def label(value) - @labels_hash[value] + if @options.key?(:localize) && @options[:localize] + I18n.t(@labels_hash[value]) + else + @labels_hash[value] + end end def labels - @labels_array ||= self.map{|e| @labels_hash[e]} + @labels_array ||= self.map{|e| label(e)} end def hash @labels_hash end def select_options - @select_options ||= self.map{|e| [@labels_hash[e], e.to_s]} + if @options.key?(:localize) && @options[:localize] + @select_options ||= self.map{|e| [I18n.t(@labels_hash[e]), e.to_s]} + else + @select_options ||= self.map{|e| [@labels_hash[e], e.to_s]} + end end - def set_label(enum_value, label_string) reset_labels @labels_hash[enum_value.to_sym] = label_string From 38f222a59bf212c163cdc2d27b788491caaac14d Mon Sep 17 00:00:00 2001 From: Alexandre Klein Date: Thu, 5 Jul 2012 15:27:53 +0900 Subject: [PATCH 2/2] DRY up localisation functions --- lib/enumerated_attribute/attribute/attribute_descriptor.rb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lib/enumerated_attribute/attribute/attribute_descriptor.rb b/lib/enumerated_attribute/attribute/attribute_descriptor.rb index d98ab86..fd8d2a9 100644 --- a/lib/enumerated_attribute/attribute/attribute_descriptor.rb +++ b/lib/enumerated_attribute/attribute/attribute_descriptor.rb @@ -40,11 +40,7 @@ def hash @labels_hash end def select_options - if @options.key?(:localize) && @options[:localize] - @select_options ||= self.map{|e| [I18n.t(@labels_hash[e]), e.to_s]} - else - @select_options ||= self.map{|e| [@labels_hash[e], e.to_s]} - end + @select_options ||= self.map{|e| [label(e), e.to_s]} end def set_label(enum_value, label_string) reset_labels