Skip to content

Commit

Permalink
Add simple attribute implementation backed by ivars
Browse files Browse the repository at this point in the history
  • Loading branch information
josh committed Jun 18, 2009
1 parent d5d5923 commit af53010
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions activemodel/lib/active_model.rb
Expand Up @@ -26,6 +26,7 @@
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'
Expand Down
17 changes: 17 additions & 0 deletions 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
30 changes: 30 additions & 0 deletions 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

0 comments on commit af53010

Please sign in to comment.