representable
representable copied to clipboard
Dynamically choosing representer for STI
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}
Hi Leo, the :decorator or :extend option is dynamic: http://trailblazer.to/gems/representable/3.0/function-api.html#extend