Skip to content

Commit

Permalink
refactor check attribute name
Browse files Browse the repository at this point in the history
  • Loading branch information
aderyabin committed Oct 15, 2015
1 parent ea187d6 commit f0ff80b
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
19 changes: 8 additions & 11 deletions lib/lotus/entity.rb
Expand Up @@ -140,15 +140,13 @@ module ClassMethods
# DeletedUser.attributes => #<Set: {:id, :name, :deleted_at}>
#
def attributes(*attrs)
if attrs.any?
attrs = Lotus::Utils::Kernel.Array(attrs)
self.attributes.merge attrs
return @attributes ||= Set.new unless attrs.any?

attrs.each do |attr|
define_attr_accessor(attr) if defined_attribute?(attr)
Lotus::Utils::Kernel.Array(attrs).each do |attr|
if allowed_attribute_name?(attr)
define_attr_accessor(attr)
self.attributes << attr
end
else
@attributes ||= Set.new
end
end

Expand All @@ -164,11 +162,10 @@ def define_attr_accessor(attr)

# Check if attr_reader define the given attribute
#
# @since 0.3.1
# @since 0.5.1
# @api private
def defined_attribute?(name)
name == :id ||
!instance_methods.include?(name)
def allowed_attribute_name?(name)
!instance_methods.include?(name)
end

protected
Expand Down
20 changes: 20 additions & 0 deletions test/entity_test.rb
Expand Up @@ -38,6 +38,11 @@ class Camera
Car.attributes.must_equal Set.new([:id, :model])
end

it 'rejects existed instance methods' do
Car.attributes :object_id
Car.attributes.must_equal Set.new([:id])
end

describe 'params is array' do
it 'defines attributes' do
Car.attributes [:model]
Expand All @@ -46,6 +51,21 @@ class Camera
end
end

describe '.allowed_attribute_name?' do
it 'returns true if attrubute not defined' do
Car.allowed_attribute_name?(:model).must_equal true
end

it 'returns false if attribute defined' do
Car.attributes :model
Car.allowed_attribute_name?(:model).must_equal false
end

it 'returns false for reserved word' do
Car.allowed_attribute_name?(:to_json).must_equal false
end
end

describe '#initialize' do
describe 'with defined attributes' do
it 'accepts given attributes' do
Expand Down

0 comments on commit f0ff80b

Please sign in to comment.