Any interest in adding a props accessor? #583
-
First, thank you contributors and maintainers for this great library. I'm so glad there's a solid option for building component based UIs in ruby/rails. My project has quite a few component classes that do nothing but set instance variables for templates from keyword arguments. For example: class SearchFieldComponent < ViewComponent::Base
def initialize(search_text:)
@search_text = search_text
end
end and class NotesLayoutComponent < ViewComponent::Base
def initialize(notes:, note:, search_text:)
@notes = notes
@note = note
@search_text = search_text
end
end I've found myself wanting a If you can remember back a few years to React's class Components, they provided a similar API with Assuming most view_component users are using keyword arguments instead of positional arguments, it would be nice to have something like this in <form>
<input
placeholder="Search"
value="<%= props.search_text %>"
/>
</form> I've already added this to my project: class BaseComponent < ViewComponent::Base
attr_reader :props
def initialize(args)
@props = OpenStruct.new(args)
end
end But, it would be nice, IMO, if that came "out of the box". Thanks for your consideration! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
This is on the hacky side to be sure, but I recently tried this out: class ApplicationComponent < ViewComponent::Base
def set_props(&block)
local_binding = block.binding
local_binding.local_variables.each do |key|
instance_variable_set :"@#{key}", local_binding.local_variable_get(key)
end
yield
end
end and then in a component subclass: class ReadMoreComponent < ApplicationComponent
def initialize(id:, url:)
set_props {}
end
end or adding extra derived "props": class PostComponent < ApplicationComponent
def initialize(post:, show_source: true, hide_hide_toggle: false)
set_props do
@source = @post.source
end
end
end That lets me make instance variables out of all keyword arguments automatically. (Magic!) |
Beta Was this translation helpful? Give feedback.
-
I recently landed better compatibility with Dry::Initializer in the |
Beta Was this translation helpful? Give feedback.
I recently landed better compatibility with Dry::Initializer in the
v4
branch: https://github.com/ViewComponent/view_component/pull/2332/files#diff-2bfab3db5cc1baf4c6d3ff6b19901926e3bdf4411ec685dac973e5fcff1c723bR17. Let me know what you think!