mutations icon indicating copy to clipboard operation
mutations copied to clipboard

Command current user awareness

Open datapimp opened this issue 11 years ago • 3 comments

Another feature that I've implemented, that I think would be very helpful for users of the mutations gem is current user awareness.

Below is a somewhat contrived example

class CreateBook < Mutations::Command
  required do
     title :string
  end

  def execute
    model_scope.create(title: title)
  end

  protected

    def model_scope
      current_user.present? ? current_user.books : Book
    end
end

would be called via:

def create
  CreateBook.as(current_user).run(params[:book])
end

If you would be interested in supporting this kind of api, I can speak to a number of great benefits over the approach of passing current user as an input.

Let me know and I will prepare a pull request

datapimp avatar Aug 23 '14 20:08 datapimp

We had a similar use-case a while back, we solved it using additional filters.

module Mutations
  class UserFilter < AdditionalFilter
    @default_options = {
      with_permission_to: []
    }

    def filter(data)
      ...
    end
  end
end

Which can be used in the mutations:

class CreateBook < Mutations::Command
  required do
     user :current_user, with_permission_to: :create_books
  end

  def execute
    ...
  end
end

eliank avatar Aug 25 '14 07:08 eliank

Likewise. That is what I've been doing and I recognize it is a subtle difference, and that subclassing works too

I think in large apps with various levels of users running commands, who is running the command is less of an input to the command itself and more a general requirement and so this helps to make a more explicit api with less noise

datapimp avatar Aug 25 '14 15:08 datapimp

@eliank just curious but what does your with_permission_to implementation actually look like? I like that a lot and would like to borrow it.

Just need some more food for thought. The gem I'm working on https://github.com/datapimp/smooth is designed to support a highly declarative style of coding up APIs (the mutations gem obviously helps a ton here) and that snippet you shared pretty much nails how I would like to work in authorization

datapimp avatar Aug 25 '14 18:08 datapimp