Sha256: d337e79f9954cbbdee7985ff4cce9faa38a96b2225259045ccd44aca481f631d

Contents?: true

Size: 1.64 KB

Versions: 3

Compression:

Stored size: 1.64 KB

Contents

$LOAD_PATH << File.dirname(__FILE__)
$LOAD_PATH << File.expand_path(File.join(__FILE__, '..', '..', 'lib'))

require 'spec_helper'
require 'babel'

class Babel::RemoteService

  def initialize(url, options = {})
    @url = url
    @options = options
    @urls = []
  end

  def resource(subject_class)
    Resource.new(subject_class, url(subject_class), @options)
  end

  def url(subject_class, path = nil)
    @urls[subject_class] = "#{@url}/#{path}" if path
    @urls[subject_class] || "#{@url}/#{subject_class.to_s.downcase}s"
  end
end

class Babel::Resource

  def initialize(subject_class, url, options = {})
    @options = options.dup
    @options[:accept] ||= :json
    @factory = Factory.new(subject_class)
    @resource = RestClient::Resource.new(url:, @options)
  end

  def member_resource(model_or_id)
    id = case model_or_id
         when String
           model_or_id
         when Fixnum
           model_or_id.to_s
         else
           model_or_id.id.to_s
         end
    @resource[id]
  end

  def get(model_or_params)
    case model_or_params
    when Hash
      @resource.get(:params => model_or_params) do |res|
        @factory.from_json(res)
      end
    else
      model_resource(model_or_params).get do |res|
        @factory.from_json(res)
      end
    end
  end

  def post(model)
    member_resource(model).post(@factory.to_json(model)) do |res|
      @factory.from_json(res)
    end
  end

  def put(model)
    member_resource(model).put(@factory.to_json(model)) do |res|
      @factory.from_json(res)
    end
  end

  def delete(model)
    member_resource(model).delete( @factory.to_json(model))
  end
end

user_service.resource(User).get

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
vellam-0.1.2 spec/resty.rb~
vellam-0.1.1 spec/resty.rb~
vellam-0.1 spec/resty.rb~