Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resource definition DSL #31

Open
aldesantis opened this issue Jul 22, 2018 · 0 comments
Open

Resource definition DSL #31

aldesantis opened this issue Jul 22, 2018 · 0 comments
Labels

Comments

@aldesantis
Copy link
Member

aldesantis commented Jul 22, 2018

Rather than requiring users to write/generate boilerplate code for each resource, it shouldn't be too hard to allow users to define resources with a DSL and provide hooks for customization, e.g.

# app/resources/api/v1/post.rb
Pragma::Resource.define :post do |config| # entire block is optional
  config.model_class = ::Post # optional, computed by default

  config.attributes do |attributes|
    attributes.define :title, :body do
      type :string
      validate :required?
    end

    attributes.define :author do
      default ->(options) { options['current_user'] }
      validate :required?
      visible false # not exposed in decorator
    end

    attributes.define :send_newsletter do
      type :boolean
      only :create # cannot be updated
      virtual # not saved to model
    end
  end

  # These would accept any callable object which receives `options`.
  # We would also have before_* and around_* hooks.
  config.hooks do |hooks|
    hooks.after_create API::V1::Post::Hook::NotifySubscribers
    hooks.after_update API::V1::Post::Hook::TouchLastUpdate
    hooks.after_save API::V1::Post::Hook::GenerateSummary
    hooks.after_destroy API::V1::Post::Hook::RemoveFromFeed
  end

  config.policy do |policy|
    policy.on :create? do |user, post|
      # ...
    end
  end
end

We should still support custom resources defined the old way.

This would probably be a separate library/gem (Pragma::Resource?) providing a catch-all API endpoint that looks at the configuration and executes the appropriate logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

1 participant