Skip to content

Instantly share code, notes, and snippets.

@joshco
Created March 9, 2015 10:04
Show Gist options
  • Save joshco/0519fad6f846a6a7fcb3 to your computer and use it in GitHub Desktop.
Save joshco/0519fad6f846a6a7fcb3 to your computer and use it in GitHub Desktop.
Making a dynamic collection representer
module Api
module V1
module CollectionRepresenter
include Roar::JSON::HAL
# include Roar::Representer::Feature::Hypermedia
#pagination
def total_pages
nil
end
def total_records
count
end
#property :page_number, getter: lambda { |args| args[:page_number] <-- that's the parameters you pass in }
def tcount
count
end
def xlass
represented.class.to_s.split(':')[0].constantize
end
def child_representer
base_class=represented.class.to_s.split(':')[0]
rep_class = 'Api::V1::' + base_class + 'Representer'
rep_class #.constantize
end
def collection_name
represented.class.to_s.underscore.split('/')[0].pluralize
end
property :tcount
property :child_representer
property :total_pages
property :per_page, getter: lambda { |args| args[:per_page] }
property :page_number, :as => 'page', getter: lambda { |args| args[:page] }
property :total_records, getter: lambda { |args| args[:total] }
options = {
class: :xlass,
extend: QuestionRepresenter,
# HELP
# I want to call a method child_representer to dynamically find the right collection item representer
# this does not work and fails with no such method or error
#
embedded: true,
#decorator_scope: true,
as: "osdi:questions"
}
collection :all, options
link :self do
cname =represented.class.to_s.underscore.split('/')[0].pluralize
send("api_v1_#{cname}_path",
only_path: false)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment