Replies: 3 comments
-
Hey Alec, thanks for opening this discussion! I've taken a very similar approach - if you haven't already, you might want to check out Joel's talk on ViewComponent at last year's RailsConf where he talks about fetch-or-fallback. One of ViewComponent's key benefits is speed. Introducing Active Model on top of this might have some implications there, and whether that part of Rails is considered stable is still a little bit contentious, though there's been talk of making its API fully public. But I've definitely seen a pattern of either Active Model or dry-initializer being used so that descendants can extend the parent class's API in a way that's nice and readable. I personally used Active Model and validations in the |
Beta Was this translation helpful? Give feedback.
-
Hi @AlecRust, it's an interesting topic! My two cents below. You could also leverage # app/components/concerns/active_model_view_component.rb
module ActiveModelViewComponent
extend ActiveSupport::Concern
included do
include ActiveModel::Model
include ActiveModel::Attributes
include ActiveModel::Validations
end
def before_render
validate!
end
end I use a similar approach with concerns such as:
But I don't use Active Model or concerns to define attributes. I prefer to use dry-initializer for this. Here is an example. |
Beta Was this translation helpful? Give feedback.
-
Thanks both for your comments really appreciate it! Some great ideas 👀 |
Beta Was this translation helpful? Give feedback.
-
We have a fair number of components and ended up with a lot of duplication for each component e.g.
Each parameter is repeated 3 or 4 times but it's not doing much:
This same setup was getting repetitive for all of our UI components so we added an abstraction to simplify it:
app/lib/active_model_view_component.rb
Component file now becomes just:
My question is basically, what do you think of this? Is there a better way we should be cutting down on this "scaffolding" for each component? Is defining parameters in just one place something that's been considered for ViewComponent, or using
ActiveModel::Attributes
?Beta Was this translation helpful? Give feedback.
All reactions