Skip to content
This repository
Browse code

Allow to read and write AR attributes with non valid identifiers

  • Loading branch information...
commit 1b7b7243062519a58286cf88411bec69cd84fa24 1 parent 7717fc3
Santiago Pastorino authored March 21, 2011
2  activerecord/lib/active_record/attribute_methods/read.rb
@@ -66,7 +66,7 @@ def define_read_method(symbol, attr_name, column)
66 66
             if cache_attribute?(attr_name)
67 67
               access_code = "@attributes_cache['#{attr_name}'] ||= (#{access_code})"
68 68
             end
69  
-            generated_attribute_methods.module_eval("def #{symbol}; #{access_code}; end", __FILE__, __LINE__)
  69
+            generated_attribute_methods.send(:define_method, symbol) { eval(access_code) }
70 70
           end
71 71
       end
72 72
 
4  activerecord/lib/active_record/attribute_methods/write.rb
@@ -10,7 +10,9 @@ module Write
10 10
       module ClassMethods
11 11
         protected
12 12
           def define_method_attribute=(attr_name)
13  
-            generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__)
  13
+            generated_attribute_methods.send(:define_method, "#{attr_name}=") do |new_value|
  14
+              write_attribute(attr_name, new_value)
  15
+            end
14 16
           end
15 17
       end
16 18
 
12  activerecord/test/cases/base_test.rb
@@ -43,6 +43,8 @@ class ReadonlyTitlePost < Post
43 43
   attr_readonly :title
44 44
 end
45 45
 
  46
+class Weird < ActiveRecord::Base; end
  47
+
46 48
 class Boolean < ActiveRecord::Base; end
47 49
 
48 50
 class BasicsTest < ActiveRecord::TestCase
@@ -461,6 +463,16 @@ def test_readonly_attributes
461 463
     assert_equal "changed", post.body
462 464
   end
463 465
 
  466
+  def test_non_valid_identifier_column_name
  467
+    weird = Weird.create('a$b' => 'value')
  468
+    weird.reload
  469
+    assert_equal 'value', weird.send('a$b')
  470
+
  471
+    weird.update_attribute('a$b', 'value2')
  472
+    weird.reload
  473
+    assert_equal 'value2', weird.send('a$b')
  474
+  end
  475
+
464 476
   def test_multiparameter_attributes_on_date
465 477
     attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "24" }
466 478
     topic = Topic.find(1)
3  activerecord/test/schema/schema.rb
@@ -651,6 +651,9 @@ def create_table(*args, &block)
651 651
     t.integer :molecule_id
652 652
     t.string :name
653 653
   end
  654
+  create_table :weirds, :force => true do |t|
  655
+    t.string 'a$b'
  656
+  end
654 657
 
655 658
 
656 659
   except 'SQLite' do

0 notes on commit 1b7b724

Please sign in to comment.
Something went wrong with that request. Please try again.