Skip to content

Dynamically choosing representer for STI #222

@goalaleo

Description

@goalaleo

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}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions