Sha256: d5328e9509f29cd1ea2f160ccf935cd30e62bf408c5ac53748a0d8678bbb3f82

Contents?: true

Size: 1.8 KB

Versions: 3

Compression:

Stored size: 1.8 KB

Contents

module Ldp
  class Orm
    attr_reader :resource
    attr_reader :last_response

    def initialize resource
      @resource = resource
    end

    def subject_uri
      resource.subject_uri
    end

    def new?
      resource.new?
    end

    def persisted?
      !new?
    end

    def graph
      Ldp.instrument 'graph.orm.ldp', subject: subject_uri do
        resource.graph
      end
    end

    def value predicate
      graph.query(:subject => subject_uri, :predicate => predicate).map do |stmt|
        stmt.object
      end
    end

    def query *args, &block
      Ldp.instrument 'query.orm.ldp', subject: subject_uri do
        graph.query *args, &block
      end
    end

    def reload
      Ldp.instrument 'reload.orm.ldp', subject: subject_uri do
        Ldp::Orm.new resource.reload
      end
    end

    def create
      Ldp.instrument 'create.orm.ldp', subject: subject_uri do
        # resource.create returns a reloaded resource which causes any default URIs (e.g. "<>")
        # in the graph to be transformed to routable URIs
        Ldp::Orm.new resource.create
      end
    end

    def save
      Ldp.instrument 'save.orm.ldp', subject: subject_uri do
        response = create_or_update

        response.success?
      end
    rescue Ldp::HttpError
      false
    end

    def save!
      result = create_or_update

      if result.is_a? RDF::Enumerable
        raise Ldp::GraphDifferenceException, 'Graph failed to persist', result
      end

      result
    end

    def delete
      Ldp.instrument 'delete.orm.ldp', subject: subject_uri do
        resource.delete
      end
    end

    private

    def create_or_update
      @last_response = resource.save
    rescue Ldp::HttpError => e
      @last_response = e
      logger.debug e
      raise e
    end

    def logger
      Ldp.logger
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ldp-1.0.3 lib/ldp/orm.rb
ldp-1.0.2 lib/ldp/orm.rb
ldp-1.0.1 lib/ldp/orm.rb