phlex-ruby / phlex

A framework for building object-oriented views in Ruby.
https://beta.phlex.fun
MIT License
1.24k stars 83 forks source link

Method to make binding the `class` kwarg easier #720

Closed bradgessler closed 2 months ago

bradgessler commented 4 months ago

Its common to want to intercept the class kwarg like this:

  def input(*, class: "hi", **, &)
    super(*, class: tokens(keyword(class:)))
  end

Phlex could have a method that makes this possible like this:

    def keyword(**bindings)
      if bindings.size > 1
        bindings.values
      else
        bindings.values.first
      end
    end

Not sure if keyword is the right method name. Some possible method names are:

bind
keyword
keywords
value
values
grab

Previous attempt at https://github.com/phlex-ruby/phlex/pull/717 broke the way tokens behaved and was less composable. I believe this approach solves both of those problems.

joeldrapper commented 3 months ago

I quite like this with the name grab. @willcosgrove what are your thoughts?

willcosgrove commented 3 months ago

I like grab too. It is solving an interesting problem. I'm kind of surprised I haven't run into a need for it yet 🤔

In the example given, I would just use mix and not have any need to grab out the class kwarg.

joeldrapper commented 3 months ago

Oh, of course you can already use mix for this. I’m trying to be very careful about what features we introduce in core, but I don’t think this represents a significant increase in complexity or maintenance burden. It’s the kind of thing that’s useful if you need it and disappears if you don’t, which I like.

joeldrapper commented 3 months ago

Even though you can technically use mix, with **mix(:class), I think something like this is quite a bit simpler when all you’re doing is passing along the class.

def foo(class:)
  div(class: [grab(class:), "some other classes here"])
end

The implementation also allows you to grab multiple values with multiple assignment, e.g.

a, b, c, d = grab(class:, end:, while:, if:)