trailblazer / roar

Parse and render REST API documents using representers.

Home Page:http://www.trailblazer.to/gems/roar

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Help with dynamic representer

joshco opened this issue · comments

commented

I'm trying to make a dynamic collection representer which will detect which representer to use for the items in the collection.
I created methods in the representer to examine the represented collection and construct the relevant constants for the representers as well as for the url helpers in the links collection.

However, these methods are out of scope for using as parameters in a collection method.
What's really got me twisted up is that it works for the class: parameter with collection, but not the extend: parameter.

How do I do this?
Please see this gist:
https://gist.github.com/joshco/0519fad6f846a6a7fcb3
Look at the comment starting with HELP

Snippets

 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

 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

@joshco Am I correct in assuming you are including your CollectionRepresenter in Decorators? In that case, you'll want to use the decorator and :exec_context options.

If so, you might find this helpful: https://github.com/summera/roar-contrib/blob/master/lib/roar/contrib/decorator/collection_representer.rb
I created Collection and Pagination Representers for use with Decorators as part of roar-contrib.

If you plan on using Representer Modules , you could take a look at Representables docs on Polymorphic Extend . Hope this helps!

commented

Thanks for this info. I'll explore it.

@joshco Is exec_context: :decorator what you want?