Accepting arguments for method defined by add_to_class

Instance methods can be added to classes by plugins using add_to_class, defined as:

def add_to_class(class_name, attr, &block)
  reloadable_patch do |plugin|
    klass = class_name.to_s.classify.constantize rescue class_name.to_s.constantize
    hidden_method_name = :"#{attr}_without_enable_check"
    klass.public_send(:define_method, hidden_method_name, &block)

    klass.public_send(:define_method, attr) do |*args|
      public_send(hidden_method_name, *args) if plugin.enabled?
    end
  end
end

Is there an existing way to do something like this, where the defined method takes arguments?

add_to_class(Guardian, :ensure_user_can_access_report, group, report) do
  ...
end
3 Likes

This seems like what you’re looking for. Makes for a good example.

So, basically, you’ll have to make those params as params to the lambda itself.

2 Likes

Yeah, thats exactly it. Thanks!

1 Like

You can do the same thing the ruby way too.