Commit c3c68ac2738c9d25717236eb96cea0c6b5d10e65
1 parent
a3292002
Exists in
master
and in
23 other branches
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
Showing
2 changed files
with
18 additions
and
4 deletions
Show diff stats
lib/acts_as_having_settings.rb
| ... | ... | @@ -22,6 +22,7 @@ module ActsAsHavingSettings |
| 22 | 22 | |
| 23 | 23 | options = names.last.is_a?(Hash) ? names.pop : {} |
| 24 | 24 | default = options[:default] ? options[:default].inspect : "val" |
| 25 | + data_type = options[:type] || :string | |
| 25 | 26 | |
| 26 | 27 | names.each do |setting| |
| 27 | 28 | class_eval <<-CODE |
| ... | ... | @@ -30,12 +31,18 @@ module ActsAsHavingSettings |
| 30 | 31 | val.nil? ? #{default} : val |
| 31 | 32 | end |
| 32 | 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 | 35 | end |
| 35 | 36 | CODE |
| 36 | 37 | end |
| 37 | 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 | 46 | end |
| 40 | 47 | |
| 41 | 48 | end | ... | ... |
test/unit/acts_as_having_settings_test.rb
| ... | ... | @@ -3,6 +3,9 @@ require File.dirname(__FILE__) + '/../test_helper' |
| 3 | 3 | class ActsAsHavingSettingsTest < Test::Unit::TestCase |
| 4 | 4 | |
| 5 | 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 | 10 | should 'store settings in a hash' do |
| 8 | 11 | block = Block.new |
| ... | ... | @@ -49,11 +52,15 @@ class ActsAsHavingSettingsTest < Test::Unit::TestCase |
| 49 | 52 | end |
| 50 | 53 | |
| 51 | 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 | 56 | obj.flag = false |
| 56 | 57 | assert_equal false, obj.flag |
| 57 | 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 | 66 | end | ... | ... |