Skip to content

Representing objects into objects using Representable::Object#to_object #267

@elShiaLabeouf

Description

@elShiaLabeouf

Hello @apotonick and the Trailblazer team!

First of all, I'd like to thank you all for the great framework you created and that you've been supporting it for all these years. It's truly great and I appreciate the work.

I met Trailblazer on an API project in 2019 and worked for 2 years with it back then.

Currently I'm working on a legacy SSR Rails 5 application with fat models and controllers and I really want to incorporate Trailblazer there to structure and organize the code.

During my first steps of trying it out on a SSR app, I came to think that it could've come in handy if Representable could make objects as output, i.e.

animal = Animal.new(name: "Barrel")
represented = AnimalRepresenter.new(animal).to_object
represented.name  # => "Barrel"

So that properties could be accessed via method calls.

Why would it be handy? For Rails view helpers, which often take an object and method names it should respond to. Plus partials would look less polluted (on a scale of hundreds variable calls in a single page) comparing to hash key-value usage:

mylongvariable["mylongerylongkey"]
# vs
mylongvariable.mylongerylongkey

I saw some developments in this direction in the Representable source code, but I couldn't make it work like in the example above. And there's no info about this mysterious to_object in the Trailblazer docs.

I decided to create a PR that adds such a feature. The usage is similar to using to_json or to_hash format options. I used Ruby Struct for represented object containers.

I would also love to add a notion about this new option to the Trailblazer documentation as well if the PR gets to master.

Looking forward to hearing your thoughts about it!

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