Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reflections #9

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/all_futures/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
module AllFutures
class InvalidAttribute < StandardError; end

class MissingForeignKeyError < StandardError; end

class ParentModelNotSavedYet < StandardError; end

class ReadOnlyRecord < StandardError; end
Expand Down
34 changes: 34 additions & 0 deletions lib/all_futures/persistence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,35 @@ def _delete_record
end

def _save_record
_reflections.each do |association, reflection|
case reflection.macro
when :embeds_many
fk = model_name.singular + "_id"
_raise_missing_foreign_key_error(reflection, fk) unless reflection.klass.has_attribute?(fk)
send(association).each do |record|
if record.new_record?
record.send("#{fk}=", @id)
record.save
end
record.destroy if record.marked_for_destruction?
end
when :embeds_one
fk = model_name.singular + "_id"
_raise_missing_foreign_key_error(reflection, fk) unless reflection.klass.has_attribute?(fk)
if (record = send(association))
if record.new_record?
record.send("#{fk}=", @id)
record.save
end
record.destroy if record.marked_for_destruction?
end
when :embedded_in
if (record = send(association))
record.save if record.new_record? && send(reflection.klass.model_name.singular + "_id").nil?
end
end
end

if versioning_enabled?
if new_record?
@_current_version = 1
Expand All @@ -162,6 +191,7 @@ def _save_record
"updated_at" => Time.current
}
end

Kredis.json(@redis_key).value = {
attributes: attributes,
created_at: created_at,
Expand All @@ -172,6 +202,10 @@ def _save_record
}
end

def _raise_missing_foreign_key_error(reflection, fk)
raise AllFutures::MissingForeignKeyError, "#{reflection.klass} missing foreign key #{fk}"
end

def _raise_readonly_attribute_error(attribute)
raise AllFutures::ReadOnlyRecord, "#{attribute} is marked as readonly"
end
Expand Down