Hey there
Is it possible to have optional attributes and a block as parameters for a method call?
Example: I have to call
method(foo, foo: bar, -> { do_something }
and tried it with
def method(foo, *bar, &block) end
As for my understanding the block always has to be at last position?
After a bit of research I found out the unary(?)
*
seems to be for arrays. Since I try to pass aHash
I changed the code todef method(foo, bar={}, &block) end
But this doesn't do the trick either. I guess its because he cant figure out where the bar ends and the block starts.
Any ideas or suggestions? Thank you in advance
Append: Just for the curious why I need this. We have a big json schema running and have a small DSL that builds the json from the model definitation. Without going to much into detail we wanted to implement exportable_scopes.
class FooBar exportable_scope :some_scope, title: 'Some Scope', -> { rewhere archived: true } end
On some initializer this is supposed to happens:
def exportable_scope scope, attributes, &block scope scope block if attributes.any? attributes.each do |attribute| exportable_schema.scopes[scope] = attribute end else exportable_schema.scopes[scope] = {title: scope} end end
So this is working fine, I just need a hint for the method parameters.
exportable_scope(:some_scope, title: 'Some Scope'){ rewhere archived: true }
。您不需要像参数一样发送块。 - Lukas Baliak.scope
期望接收的。范围的主体是必需的,因此您可以将方法签名更改为exportable_scope(name, body, attributes = {})
并调用scope name, body
。在这里查看.scope
定义:https://github.com/rails/rails/blob/dc925119a3912ecfe0df400007163f33b99d6385/activerecord/lib/active_record/scoping/named.rb#L143。`exportable_scope :some_scope, -> { rewhere archived: true }, title: 'Some Scope'`。 - Alexandre Angelim