Commit c3c68ac2738c9d25717236eb96cea0c6b5d10e65

Authored by AntonioTerceiro
1 parent a3292002

ActionItem394: adding type support for acts_as_having_settings


git-svn-id: https://svn.colivre.coop.br/svn/noosfero/trunk@1800 3f533792-8f58-4932-b0fe-aaf55b0a4547
lib/acts_as_having_settings.rb
@@ -22,6 +22,7 @@ module ActsAsHavingSettings @@ -22,6 +22,7 @@ module ActsAsHavingSettings
22 22
23 options = names.last.is_a?(Hash) ? names.pop : {} 23 options = names.last.is_a?(Hash) ? names.pop : {}
24 default = options[:default] ? options[:default].inspect : "val" 24 default = options[:default] ? options[:default].inspect : "val"
  25 + data_type = options[:type] || :string
25 26
26 names.each do |setting| 27 names.each do |setting|
27 class_eval <<-CODE 28 class_eval <<-CODE
@@ -30,12 +31,18 @@ module ActsAsHavingSettings @@ -30,12 +31,18 @@ module ActsAsHavingSettings
30 val.nil? ? #{default} : val 31 val.nil? ? #{default} : val
31 end 32 end
32 def #{setting}=(value) 33 def #{setting}=(value)
33 - send(self.class.settings_field)[:#{setting}] = value 34 + send(self.class.settings_field)[:#{setting}] = self.class.acts_as_having_settings_type_cast(value, #{data_type.inspect})
34 end 35 end
35 CODE 36 CODE
36 end 37 end
37 end 38 end
38 39
  40 + def acts_as_having_settings_type_cast(value, type)
  41 + # FIXME creating a new instance at every call, will the garbage collector
  42 + # be able to cope with it?
  43 + ActiveRecord::ConnectionAdapters::Column.new(:dummy, nil, type.to_s).type_cast(value)
  44 + end
  45 +
39 end 46 end
40 47
41 end 48 end
test/unit/acts_as_having_settings_test.rb
@@ -3,6 +3,9 @@ require File.dirname(__FILE__) + &#39;/../test_helper&#39; @@ -3,6 +3,9 @@ require File.dirname(__FILE__) + &#39;/../test_helper&#39;
3 class ActsAsHavingSettingsTest < Test::Unit::TestCase 3 class ActsAsHavingSettingsTest < Test::Unit::TestCase
4 4
5 # using Block class as a sample user of the module 5 # using Block class as a sample user of the module
  6 + class TestClass < Block
  7 + settings_items :flag, :type => :boolean
  8 + end
6 9
7 should 'store settings in a hash' do 10 should 'store settings in a hash' do
8 block = Block.new 11 block = Block.new
@@ -49,11 +52,15 @@ class ActsAsHavingSettingsTest &lt; Test::Unit::TestCase @@ -49,11 +52,15 @@ class ActsAsHavingSettingsTest &lt; Test::Unit::TestCase
49 end 52 end
50 53
51 should 'be able to set boolean attributes to false with a default of true' do 54 should 'be able to set boolean attributes to false with a default of true' do
52 - klass = Class.new(Block)  
53 - klass.settings_items :flag, :default => true  
54 - obj = klass.new 55 + obj = TestClass.new
55 obj.flag = false 56 obj.flag = false
56 assert_equal false, obj.flag 57 assert_equal false, obj.flag
57 end 58 end
58 59
  60 + should 'be able to specify type of atrributes (boolean)' do
  61 + obj = TestClass.new
  62 + obj.flag = 'true'
  63 + assert_equal true, obj.flag
  64 + end
  65 +
59 end 66 end