lib/billogram/resource.rb in billogram-0.0.1 vs lib/billogram/resource.rb in billogram-0.2.0

- old
+ new

@@ -1,61 +1,52 @@ module Billogram class Resource + attr_reader :data + + DEFAULT_OPTIONS = { page: 1, page_size: 2 } + class << self - attr_writer :endpoint + def relations + @relations ||= { one: Set.new, many: Set.new } + end - def endpoint - @endpoint || downcased_class_name + def endpoint(value = nil) + @endpoint = value if value + @endpoint || name.demodulize.underscore.pluralize end - def get(id = '') - get_and_return_new("/#{endpoint}/#{id}") + def search(options = {}) + query = DEFAULT_OPTIONS.merge(options) + response = Billogram.client.get("#{endpoint}", {query: query}) + parse_response(response.parsed_response["data"]) end - private + def fetch(id) + response = Billogram.client.get("#{endpoint}/#{id}") + parse_response(response.parsed_response["data"]) + end - def downcased_class_name - name.split('::').last.downcase + def parse_response(data) + # TODO: refactor, error handling + case data + when Hash then new(data) + when Array then data.map{|item| parse_response(item) } + when nil + else data + end end - def get_and_return_new(url) - response = Billogram.client.get(url) - new response['data'] + def relation(relation_name, relation_type = :one) + relations[relation_type] << relation_name + attr_reader relation_name end end - attr_reader :attributes - def initialize(attributes = {}) - @attributes = Hashie::Mash.new(attributes) - end - - def update(attributes = {}) - Billogram.client.put("/#{endpoint}/#{id}", attributes) - end - - def delete - Billogram.client.delete("/#{endpoint}/#{id}") - end - - private - - def method_missing(method, *args) - method_name = method.to_s - - if method_name =~ /(=|\?)$/ - case $1 - when '=' - attributes[$`] = args.first - when '?' - attributes[$`] - end - else - if attributes.respond_to?(method) - attributes[method] - else - super - end + Hash(attributes).each do |key, value| + instance_variable_set("@#{key}", value) if respond_to?(key) end + + RelationBuilder.new(self, attributes).call end end end