Sha256: 11fe1bf5f7d31543e9b990ab0393d7fb14700d5db1e946e4e010d4d05692748e

Contents?: true

Size: 1.74 KB

Versions: 1

Compression:

Stored size: 1.74 KB

Contents

module Jaysus
  module Remote    
    def self.base_url
      @base_url ||= ''
    end
    
    def self.base_url=(url)
      @base_url = url
    end
    
    def self.included(base)
      base.extend(ClassMethods)
    end
    
    def destroy
      super do
        RestClient.delete(remote_url,{
          'Accept' => 'application/json'
        })
      end
    end
    
    def save
      super do
        response = if pk = self.send(self.class.model_base.primary_key)
          RestClient.put("#{self.class.model_url}/#{pk}", self.to_json, {
            'Content-Type' => 'application/json',
            'Accept' => 'application/json'
          })
        else
          RestClient.post(self.class.model_url, self.to_json, {
            'Content-Type' => 'application/json',
            'Accept' => 'application/json'
          })
        end
        decoded_response = ActiveSupport::JSON.decode(
          response
        )[self.class.singular_object_name]
        self.set_attributes(decoded_response)
        self
      end
    end
    
    def remote_url
      pk = self.send(self.class.model_base.primary_key)
      return if pk.blank?
      "#{self.class.model_url}/#{pk}"
    end
    
    module ClassMethods
      def model_url
        "#{Jaysus::Remote.base_url}/#{self.plural_object_name}"
      end
      
      def all
        records = []
        ActiveSupport::JSON.decode(RestClient.get(model_url,{
          'Accept' => 'application/json'
        })).each do |raw_record|
          records << new(raw_record[self.singular_object_name])
        end
        records
      end
      
      def find(id)
        super do
          RestClient.get("#{model_url}/#{id}",{
            'Accept' => 'application/json'
          })
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
jaysus-0.1.4 lib/jaysus/remote.rb