jsonapi-suite / jsonapi_compliable

MIT License
20 stars 35 forks source link

1.0 attribute fire #112

Closed richmolj closed 6 years ago

richmolj commented 6 years ago

This introduces a resource-level attributes API:

class EmployeeResource < ApplicationResource
  # basic
  attribute :first_name, :string

  # is the same as
  attribute :first_name, :string,
    readable: true, writable: true, sortable: true, filterable: true

  # writable and filterable can be required
  attribute :first_name, :string, filterable: :required

  # All of them accept a method name (of the resource)
  attribute :first_name, :string, filterable: :admin?

  # creates a read-only (by default) extra attribute
  extra_attribute :salary

  # defaults can be modified in your ApplicationResource
  self.attributes_readable_by_default = false
  self.attributes_writable_by_default = false
  self.attributes_sortable_by_default = false
  self.attributes_filterable_by_default = false

  # pass a block for serialization
  attribute :first_name, :string do
    @object.first_name.upcase
  end

  # you can still have a separate serializer when logic gets heavy
  # this would ONLY need customizations, not the full attribute list
  self.serializer = EmployeeSerializer

  # override sort logic
  sort :title do |scope, dir|
    scope.joins(:position).order("positions.title #{dir}")
  end

  # override filter logic
  filter :title do |scope, value|
    scope.joins(:position).where(positions: { title: value })
  end

  # relationships get readable/writable too
  has_many :positions, readable: false

  # you can modify the scoping however you'd like
  def around_scoping(scope, query_hash)
    if query_hash[:extra_fields][type].include?(:salary)
      scope = scope.includes(:salary_info)
    end
    yield scope
  end
end

Serializers are now optional, strong resources and spec payloads will be removed in subsequent commits.

To get a further idea, spec/resource_spec.rb and spec/serialization_spec.rb are good examples in addition to spec/fixtures/legacy.rb.

To accomplish this:

Other:

richmolj commented 6 years ago

@wadetandy on top of https://github.com/jsonapi-suite/jsonapi_compliable/pull/111

richmolj commented 6 years ago

Now in 1.0.0-dev branch. Feedback will be addressed in future commits.