Skip to content

Commit

Permalink
Merge branch 'arraymodelsubclass' of https://github.com/alexandred/volt
Browse files Browse the repository at this point in the history
… into alexandred-arraymodelsubclass
  • Loading branch information
ryanstout committed Sep 18, 2015
2 parents 503a743 + 31fbf6b commit 0f441cc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 12 deletions.
40 changes: 28 additions & 12 deletions lib/volt/models/helpers/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,27 +74,43 @@ module ClassMethods
# Gets the class for a model at the specified path.
def class_at_path(path)
if path
begin
# remove the _ and then singularize/pluralize
if path.last == :[]
index = -2
else
index = -1
end
# remove the _ and then singularize/pluralize
if path.last == :[]
index = -2
else
index = -1
end

# process_class_name is defined by Model/ArrayModel as
# singularize/pluralize
klass_name = process_class_name(klass_name = path[index]).camelize
# process_class_name is defined by Model/ArrayModel as
# singularize/pluralize
klass_name = process_class_name(klass_name = path[index]).camelize

begin
# Lookup the class
klass = Object.const_get(klass_name)

# Use it if it is a model
klass = self unless klass < self
return (klass < self ? klass : (klass = self))
rescue NameError => e
# Ignore exception, just means the model isn't defined
klass = self
#
return klass = self if klass_name.singular?
end

# Checl for special case where we are subclassing a Volt::Model that has a custom Volt::ArrayModel
begin
# Get the pluralised name of the superclass of the model
super_klass_name = Object.const_get(klass_name.singularize).superclass.to_s.pluralize

# Get the class, rescue if not found
klass = Object.const_get(super_klass_name)

klass = self unless klass < self
rescue NameError => e
# Ignore exception, array model isn't defined.
return klass = self
end

else
klass = self
end
Expand Down
9 changes: 9 additions & 0 deletions spec/models/model_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ class Item < Volt::Model
class Items < Volt::ArrayModel
end

class SubItem < Item
end

class TestAssignsMethod < Volt::Model
def name=(val)
self._name = val
Expand Down Expand Up @@ -621,4 +624,10 @@ def name=(val)
model._items << {}
expect(model._items).to be_instance_of Items
end

it 'assigns the superclass\'s custom ArrayModel if it exists' do
model = Volt::Model.new
model._sub_items << {}
expect(model._sub_items).to be_instance_of Items
end
end

0 comments on commit 0f441cc

Please sign in to comment.