Created
November 16, 2012 13:24
-
-
Save krisleech/4087333 to your computer and use it in GitHub Desktop.
domain and persistence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Domain::Trip | |
include Virtus | |
include ActiveModel::Validations | |
include ActiveModel::Conversion | |
extend ActiveModel::Naming | |
attribute :id | |
attribute :name | |
attribute :sections, Array[Section], :default => [] | |
end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Persistence::Trip < ActiveRecord::Base | |
def self.find_by_id(id) | |
record = super(id) | |
Domain::Trip.new(record.attributes).tap do |trip| | |
trip.sections = record.sections.map { |section_record| Domain::Trip::Section.new(section_record.attributes) } | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def show | |
@trip = Persistence::Trip.find(params[:id) | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- @trip.sections.each do |section| | |
= section.name |
I think you probably have two different value objects there then: a TripSummary
for the index page, with a shallow cut of the data, and a Trip
with the deep set of data. I'd just put the queries for those behind two separate methods.
Thanks - I like the idea of having TripSummary
, after all it does not need to contain any validations, or anything else that acts on state changes, its being used in a read-only context. I guess I need to get over fear of adding classes which have overlapping responsibilities, its marginally less DRY but simpler than trying cram everything in to one class.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've played with Virtus and nested hashes, AR#attributes does not return a deep hash, but as you say it could easily be done. I think my problem is more do with the API of the persistence class - what should the different calls to the persistence class look like. If say I want to fetch a trip and all its associations (e.g show action) versus just the trip (e.g index action).