Sha256: 11668840a2d62f31a716695e75de36873a94bacd1d5e065760f3dc4ef184a661

Contents?: true

Size: 1.76 KB

Versions: 1

Compression:

Stored size: 1.76 KB

Contents

module Pige::Client
  class Resource
    include HTTParty

    # debug_output $stderr
    format :json

    def initialize(attributes = {})
      attributes.each { |k,v| send "#{k}=", v }
    end

    def self.time_attribute(*names)
      names.each do |time_attribute|
        define_method("#{time_attribute}=") do |value|
          value = Time.parse(value) if String === value
          instance_variable_set "@#{time_attribute}", value
        end
      end
    end

    attr_accessor :created_at, :updated_at
    time_attribute :created_at, :updated_at

    attr_accessor :errors
    def errors
      @errors ||= []
    end

    attr_accessor :id, :source_id

    def older_than?(date)
      self.created_at < date
    end

    def destroy
      self.class.destroy(self)
    end

    def self.resource_name
      name.downcase.split("::").last
    end

    def self.resources_name
      "#{resource_name}s"
    end

    def self.base_url
      "#{Pige::Client.box_url}/sources/1/#{resource_name}s"
    end

    def self.create(attributes = {})
      response = post("#{base_url}.json", :query => { resource_name => attributes })
      if [200,201].include? response.code
        new response
      end
    end

    def self.all
      get("#{Pige::Client.box_url}/sources/1/#{resources_name}.json").map do |attributes|
        new attributes
      end
    end

    def self.older_than(date)
      all.select do |resource|
        resource.older_than?(date)
      end
    end

    def self.destroy_all(conditions = {})
      resources =
        if older_than = conditions[:older_than]
          older_than(older_than)
        else
          all
        end

      resources.each(&:destroy)
    end

    def self.destroy(resource)
      delete "#{base_url}/#{resource.id}.json"
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tryphon-pige-client-1.0.3 lib/pige/client/resource.rb