trailblazer / representable

Maps representation documents from and to Ruby objects. Includes JSON, XML and YAML support, plain properties and compositions.
http://trailblazer.to/2.1/docs/representable.html
MIT License
689 stars 108 forks source link

Dynamically choosing representer for STI #222

Open goalaleo opened 7 years ago

goalaleo commented 7 years ago

This is a question

Hi!

Lets say that I have

class TodoList < ActiveRecord::Base
  belongs_to :user
  has_many :todo_items
end

And I use acts_as_list to track priority of TodoItem´s.

class TodoItem < ActiveRecord::Base
  acts_as_list scope: :todo_list, column: :priority
end

I want to have different kinds of TodoItems, so I'll use STI

class PersonalItem < TodoItem
end
class SharedItem < TodoItem
end

I'll also define respective representers

class TodoItemRepresenter < Representable::Decorator
  # define shared properties here  
end
# inherit TodoItemRepresenter for subclass representers
class PersonalItemRepresenter < TodoItemRepresenter
  # properties specific for PersonalItems
end

class SharedItemRepresenter < TodoItemRepresenter
  # properties specific for SharedItem
end

Now the question is: is there a built in way to dynamically choose the correct representer based on the actual class? I'd prefer to call something similar to .for_collection.new(user.todo_items) instead of doing something like

user.todo_items.map{|todo_item| (todo_item.type + "Representer").constantize.new(todo_item).to_hash}
apotonick commented 7 years ago

Hi Leo, the :decorator or :extend option is dynamic: http://trailblazer.to/gems/representable/3.0/function-api.html#extend