Skip to content

Commit

Permalink
A cross project validation. Project factory.
Browse files Browse the repository at this point in the history
  • Loading branch information
mjy committed Nov 27, 2013
1 parent 36f194e commit febb462
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 7 deletions.
23 changes: 18 additions & 5 deletions lib/housekeeping/projects.rb
Expand Up @@ -4,19 +4,24 @@ module Housekeeping::Projects
extend ActiveSupport::Concern

included do
# not added tot he model, just used to extend models here
related_instances = self.name.demodulize.underscore.pluralize.to_sym
related_class = self.name

# these are added to the model
belongs_to :project, inverse_of: related_instances

before_validation :set_project_id, on: :create

validates :project, presence: true

Project.class_eval do
raise 'Class name collision for Project#has_many' if self.methods.include?(:related_instances)
has_many related_instances, inverse_of: :project, class_name: related_class
end
before_save :prevent_alteration_in_other_projects
before_destroy :prevent_alteration_in_other_projects

# Also extend the project
Project.class_eval do
raise 'Class name collision for Project#has_many' if self.methods.include?(:related_instances)
has_many related_instances, inverse_of: :project, class_name: related_class
end
end

module ClassMethods
Expand All @@ -26,5 +31,13 @@ def set_project_id
self.project_id ||= $project_id
end

# This will have to be extended via role exceptions, maybe. It is a loose
# check here, ripped right from mx.
def prevent_alteration_in_other_projects
unless (self.project_id == $project_id)
raise 'Not owned by current project: ' + self.name + '#' + self.id.to_s
end
end

end

Expand Up @@ -4,4 +4,8 @@
factory :project do
name "MyString"
end

factory :valid_project, class: Project do
name "MyString"
end
end
22 changes: 20 additions & 2 deletions spec/lib/housekeeping_spec.rb
Expand Up @@ -45,8 +45,6 @@
@i.valid?
expect(@i.errors.include?(:updater)).to be_true # there is no project with id 1 in the present paradigm
end


end
end

Expand Down Expand Up @@ -95,6 +93,26 @@
expect(@i.errors.include?(:project)).to be_true # there is no project with id 1 in the present paradigm
end

context 'belonging to a project' do
before(:all) {
@project1 = FactoryGirl.create(:valid_project)
@project2 = FactoryGirl.create(:valid_project)
}
after(:all) {
$project_id = 1 # now return to our regular scheduled programming
}

specify 'instance must belong to the project before save' do
$project_id = @project1.id
expect(@i.valid?).to be_true
expect(@i.project_id).to eq(@project1.id)
expect(@i.save).to be_true

@i.project_id = @project2.id
expect{@i.save}.to raise_error
end

end
end
end
end
Expand Down

0 comments on commit febb462

Please sign in to comment.