Sha256: 7a51d27c9d9141e8df8c35e666a07d73524b6281153f2f5fba6e11572e3fdab1

Contents?: true

Size: 1.41 KB

Versions: 2

Compression:

Stored size: 1.41 KB

Contents

module Siteleaf
  class Entity
  
    attr_reader :error, :message

    def initialize(attributes = {})
      self.attributes = attributes
    end

    def self.all
      result = Client.get endpoint
      result.map { |r| new(r) } if result.is_a? Array
    end

    def self.find(identifier)
      result = Client.get "#{endpoint}/#{identifier}"
      new(result) if result
    end

    def self.create(attributes = {})
      new(attributes).save
    end
    
    def self.delete(identifier)
      Client.delete "#{endpoint}/#{identifier}"
    end

    def save
      if identifier
        result = Client.put entity_endpoint, attributes
      else
        result = Client.post create_endpoint, attributes
      end
      if result
        self.attributes = result
        return self
      end
    end

    def delete
      Client.delete entity_endpoint
    end

    def attributes
      Hash[self.instance_variables.map { |name| [name[1..-1], self.instance_variable_get(name)] }]
    end

    def attributes=(attributes = {})
      attributes.each_pair { |k, v| self.instance_variable_set("@#{k}", v) }
    end

    def self.class_name
      self.name.split('::')[-1]
    end

    def self.endpoint
      "#{self.class_name.downcase}s"
    end

    def create_endpoint
      self.class.endpoint
    end
    
    def entity_endpoint
      "#{self.class.endpoint}/#{identifier}"
    end
    
    def identifier
      id
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
siteleaf-2.0.0 lib/siteleaf/entity.rb
siteleaf-2.0.0.pre.beta9 lib/siteleaf/entity.rb