aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJoshua Peek <josh@joshpeek.com>2009-06-17 20:36:21 -0500
committerJoshua Peek <josh@joshpeek.com>2009-06-17 21:27:54 -0500
commitaf5301089f38b9aad9a92424d5fa8f9a9b27c4e1 (patch)
tree1f808631d86b4eaa3fbea891fb6ce285a5ab0171
parentd5d59230f4d8f0457fc793446a3dbcdce0057a78 (diff)
downloadrails-af5301089f38b9aad9a92424d5fa8f9a9b27c4e1.tar.gz
rails-af5301089f38b9aad9a92424d5fa8f9a9b27c4e1.tar.bz2
rails-af5301089f38b9aad9a92424d5fa8f9a9b27c4e1.zip
Add simple attribute implementation backed by ivars
-rw-r--r--activemodel/lib/active_model.rb1
-rw-r--r--activemodel/lib/active_model/attributes.rb17
-rw-r--r--activemodel/test/cases/attributes_test.rb30
3 files changed, 48 insertions, 0 deletions
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
index f8e5725e9c..048f542239 100644
--- a/activemodel/lib/active_model.rb
+++ b/activemodel/lib/active_model.rb
@@ -26,6 +26,7 @@ $:.unshift(activesupport_path) if File.directory?(activesupport_path)
require 'active_support'
module ActiveModel
+ autoload :Attributes, 'active_model/attributes'
autoload :Base, 'active_model/base'
autoload :DeprecatedErrorMethods, 'active_model/deprecated_error_methods'
autoload :Errors, 'active_model/errors'
diff --git a/activemodel/lib/active_model/attributes.rb b/activemodel/lib/active_model/attributes.rb
new file mode 100644
index 0000000000..4665525281
--- /dev/null
+++ b/activemodel/lib/active_model/attributes.rb
@@ -0,0 +1,17 @@
+require 'active_support/core_ext/object/instance_variables'
+
+module ActiveModel
+ module Attributes
+ def attributes
+ instance_values
+ end
+
+ def read_attribute(attr_name)
+ instance_variable_get(:"@#{attr_name}")
+ end
+
+ def write_attribute(attr_name, value)
+ instance_variable_set(:"@#{attr_name}", value)
+ end
+ end
+end
diff --git a/activemodel/test/cases/attributes_test.rb b/activemodel/test/cases/attributes_test.rb
new file mode 100644
index 0000000000..5f3ea839a4
--- /dev/null
+++ b/activemodel/test/cases/attributes_test.rb
@@ -0,0 +1,30 @@
+require 'cases/helper'
+
+class AttributesTest < ActiveModel::TestCase
+ class Person
+ include ActiveModel::Attributes
+ attr_accessor :name
+ end
+
+ test "reads attribute" do
+ p = Person.new
+ assert_equal nil, p.read_attribute(:name)
+
+ p.name = "Josh"
+ assert_equal "Josh", p.read_attribute(:name)
+ end
+
+ test "writes attribute" do
+ p = Person.new
+ assert_equal nil, p.name
+
+ p.write_attribute(:name, "Josh")
+ assert_equal "Josh", p.name
+ end
+
+ test "returns all attributes" do
+ p = Person.new
+ p.name = "Josh"
+ assert_equal({"name" => "Josh"}, p.attributes)
+ end
+end