Sha256: 1e5a4f8ee81032d2562ca2729075886fce323eb8d5d56e30cdac1337e5e8a46e

Contents?: true

Size: 1.4 KB

Versions: 7

Compression:

Stored size: 1.4 KB

Contents

# frozen_string_literal: true

module Haku
  module Resourceable
    def create_resource(parent, attributes, ivar=nil, singleton: nil)
      parent.send(singleton ? "create_#{singleton}" : "create", attributes).tap do |resource|
        instance_variable_set("@#{ivar}", resource) if ivar.present?

        if resource.persisted?
          yield resource if block_given?
          success! resource: resource
        else
          failure! resource: resource, errors: resource.errors
        end
      end
    end

    def update_resource(resource, attributes)
      resource.tap do
        if resource.update(attributes)
          yield resource if block_given?
          success! resource: resource
        else
          failure! resource: resource, errors: resource.errors
        end
      end
    end

    def destroy_resource(resource)
      resource.tap do
        if resource.destroy
          yield resource if block_given?
          success! resource: resource
        else
          failure! resource: resource, errors: resource.errors
        end
      end
    end

    def persist_resource(resource, **save_options)
      resource.tap do
        if resource.save(save_options)
          yield resource if block_given?
          success! resource: resource
        else
          failure! resource: resource, errors: resource.errors
        end
      end
    end

    alias save_resource persist_resource
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
haku-1.5.0 lib/haku/resourceable.rb
haku-1.4.0 lib/haku/resourceable.rb
haku-1.3.1 lib/haku/resourceable.rb
haku-1.3.0 lib/haku/resourceable.rb
haku-1.2.1 lib/haku/resourceable.rb
haku-1.2.0 lib/haku/resourceable.rb
haku-1.1.0 lib/haku/resourceable.rb