module Her::Model::ORM

This module adds ORM-like capabilities to the model

Public Instance Methods

destroy(params = {}) click to toggle source

Destroy a resource

@example

@user = User.find(1)
@user.destroy
# Called via DELETE "/users/1"
# File lib/her/model/orm.rb, line 76
def destroy(params = {})
  method = self.class.method_for(:destroy)
  run_callbacks :destroy do
    self.class.request(params.merge(:_method => method, :_path => request_path)) do |parsed_data, response|
      assign_attributes(self.class.parse(parsed_data[:data])) if parsed_data[:data].any?
      @metadata = parsed_data[:metadata]
      @response_errors = parsed_data[:errors]
      @destroyed = true
    end
  end
  self
end
destroyed?() click to toggle source

Return whether the object has been destroyed

# File lib/her/model/orm.rb, line 20
def destroyed?
  @destroyed == true
end
new?() click to toggle source

Return `true` if a resource was not saved yet

# File lib/her/model/orm.rb, line 9
def new?
  id.nil?
end
Also aliased as: new_record?
new_record?()
Alias for: new?
persisted?() click to toggle source

Return `true` if a resource is not `#new?`

# File lib/her/model/orm.rb, line 15
def persisted?
  !new?
end
save() click to toggle source

Save a resource and return `false` if the response is not a successful one or if there are errors in the resource. Otherwise, return the newly updated resource

@example Save a resource after fetching it

@user = User.find(1)
# Fetched via GET "/users/1"
@user.fullname = "Tobias Fünke"
@user.save
# Called via PUT "/users/1"

@example Save a new resource by creating it

@user = User.new({ :fullname => "Tobias Fünke" })
@user.save
# Called via POST "/users"
# File lib/her/model/orm.rb, line 38
def save
  callback = new? ? :create : :update
  method = self.class.method_for(callback)

  run_callbacks callback do
    run_callbacks :save do
      params = to_params.merge(:_method => method, :_path => request_path)
      self.class.request(params) do |parsed_data, response|
        assign_attributes(self.class.parse(parsed_data[:data])) if parsed_data[:data].any?
        @metadata = parsed_data[:metadata]
        @response_errors = parsed_data[:errors]

        return false if !response.success? || @response_errors.any?
        if self.changed_attributes.present?
          @previously_changed = self.changed_attributes.clone
          self.changed_attributes.clear
        end
      end
    end
  end

  self
end
save!() click to toggle source

Similar to save(), except that ResourceInvalid is raised if the save fails

# File lib/her/model/orm.rb, line 63
def save!
  if !self.save
    raise Her::Errors::ResourceInvalid, self
  end
  self
end