DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

organize the authorizations of the banken/pundit gem with define_method

🔗 Parent Note

banken is ...,

Simple and lightweight authorization library for Rails inspired by Pundit. Banken provides a set of helpers which restricts what resources a given user is allowed to access.

🤔 Situation

Authorization will be grown with your app, and it will be like this.

new? refers show?, show? refers index?.

class BooksLoyalty < ApplicationLoyalty
  def index?
    @user_context.user == @record.user
  end
  def show?
    index?
  end
  def new?
    show?
  end
end

👍 Solution

Because each method is the same, they don't transfer their logic. Then, define_method may be nice.

class BooksLoyalty < ApplicationLoyalty
  [:index?, :show?, :new?].each do |method|
    define_method method do
      @user_context.user == @record.user
    end
  end
end

If you need arguments, see also 📚 my github note.

Top comments (0)