Created
January 27, 2012 15:16
-
-
Save LevelbossMike/1689243 to your computer and use it in GitHub Desktop.
instance variables with roar to dry up representers
This file contains 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
# use case: | |
# user has_many sport_sessions | |
# I want to return sport_sessions for a user week for week | |
# depending on given weekday | |
# module for DCI mixin | |
module UserRoles | |
module TrainingWeekRepresenter | |
include Roar::Representer::JSON | |
require "#{RAILS_ROOT}/app/models/sport_session/training_day_representer_role.rb" | |
property :full_name | |
collection :sport_sessions_for_week, :class => SportSession, :extend => SportSession::TrainingDayRepresenter | |
def setup_for_representation(datetime) | |
@datetime = datetime | |
end | |
def sport_sessions_for_week | |
self.sport_sessions.where(:start_time.gt => (@[email protected]_of_week)) | |
end | |
end | |
end | |
# inside controller | |
# representer can now be used for any | |
# datetime and will return sport sessions | |
# for the corresponding week | |
def week_representation | |
user = User.find(params[:id]) | |
user.extend_with_roles [:training_week_representer] | |
user.setup_for_representation(params[:datetime]).to_json | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Something like that would be cool:
This implies that you must provide parameters from outside but it still does not rely on internal state. Of course, your solution works great but it makes your code vulnerable if a user is not following your life-cycle protocol (create user, extend, setup internals, render).