Skip to content

Commit

Permalink
Merge pull request #2 from plukevdh/inheritance-fix
Browse files Browse the repository at this point in the history
fix inheritance issues
  • Loading branch information
plukevdh committed Feb 10, 2015
2 parents 8f401db + 9ed5fdd commit 5d0580d
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/schemad/entity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class Entity
extend Schemad::Extensions

def self.inherited(subclass)
subclass.instance_variable_set(:@attributes, [])
subclass.instance_variable_set(:@attributes, inherited_attrs)
end

def self.attribute(name, args={}, &block)
Expand Down Expand Up @@ -45,6 +45,10 @@ def to_hash
alias_method :attributes, :to_hash

private
def self.inherited_attrs
parent_attrs = self.instance_variable_get(:@attributes)
default_attrs = (parent_attrs ? parent_attrs.dup : [])
end

def self.define_parser_for(name, args, &block)
define_method "parse_#{name}" do |data|
Expand Down
54 changes: 54 additions & 0 deletions spec/entity_spec.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require 'spec_helper'
require 'timecop'
require 'schemad/default_types'
require 'schemad/entity'

require_relative 'fixtures/demo_class'
Expand Down Expand Up @@ -53,4 +54,57 @@
}}
end
end

context "inherited entities" do
class Base < Schemad::Entity
attribute :name
end

class Sub < Base
attribute :place
end

context "via setters" do
Given(:parent) { Base.new }
Given(:child) { Sub.new }

context "parent has top-level attributes" do
When { parent.name = "Whil Wheaton" }
Then { parent.name.should == "Whil Wheaton" }
end

context "parent does not get child attributes" do
When(:result) { parent.place }
Then { expect(result).to have_failed(NoMethodError) }
end

context "child has all attributes" do
Given do
child.name = "Bill Cosby"
child.place = "NY, NY"
end
Then { child.name.should == "Bill Cosby" }
And { child.place.should == "NY, NY" }
end
end

context 'via #from_data' do
Given(:parent) { Base.from_data({ name: "Whil Wheaton", place: "Burt's Bees" }) }

context "parent has top-level attributes" do
Then { parent.name.should == "Whil Wheaton" }
end

context "parent does not get child attributes" do
When(:result) { parent.place }
Then { expect(result).to have_failed(NoMethodError) }
end

context "child has all attributes" do
Given(:child) { Sub.from_data({ name: "Jim Beam", place: "Black, Not" }) }
Then { child.name.should == "Jim Beam" }
And { child.place.should == "Black, Not" }
end
end
end
end

0 comments on commit 5d0580d

Please sign in to comment.