Skip to content

Instantly share code, notes, and snippets.

@LevelbossMike
Created January 27, 2012 15:16
Show Gist options
  • Save LevelbossMike/1689243 to your computer and use it in GitHub Desktop.
Save LevelbossMike/1689243 to your computer and use it in GitHub Desktop.
instance variables with roar to dry up representers
# 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 => (@datetime.beginning_of_week...@datetime.end_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
@apotonick
Copy link

Something like that would be cool:

user.to_json do ..
  :sport_sessons_for_week => user.sport_sessions_for_week(params[:datetime])

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment