Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add simple attribute implementation backed by ivars
- Loading branch information
Showing
3 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |