Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically choosing representer for STI #222

Open
goalaleo opened this issue Nov 20, 2017 · 1 comment
Open

Dynamically choosing representer for STI #222

goalaleo opened this issue Nov 20, 2017 · 1 comment

Comments

@goalaleo
Copy link

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
Copy link
Member

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants