json_api_client icon indicating copy to clipboard operation
json_api_client copied to clipboard

Mark resource as readonly

Open lcpriest opened this issue 6 years ago • 1 comments

I was scouting around the code base and was unable to find a readonly or immutable class method or include for defining a readonly resource.

Is this something available currently?

If not, I think a simple solution might be to override the save method and raise an ResourceImmutableError. Would appreciate if you can think of any side effects of that off the top of your head.

lcpriest avatar May 24 '19 02:05 lcpriest

hi @lcpriest Contributions are welcome =) I think we can add it on resource level something like this will be enough

class JsonApiClient::Resource
  class_attribute :_immutable, instance_writer: false, default: false

  def self.immutable(flag = true)
    self._immutable = flag
  end

  def self.inherited(subclass)
    subclass._immutable = false
  end

  def self.custom_endpoint(name, options = {})
    if _immutable
      request_method = options.fetch(:request_method, :get).to_sym
      raise JsonApiClient::Errors::ResourceImmutableError if request_method != :get
    end
  end

  def save
    raise JsonApiClient::Errors::ResourceImmutableError if _immutable
    # ...
  end

  def destroy
    raise JsonApiClient::Errors::ResourceImmutableError if _immutable
    # ...
  end
end

senid231 avatar May 24 '19 13:05 senid231