Skip to content

Instantly share code, notes, and snippets.

@stupakov
Created December 24, 2012 04:08
Show Gist options
  • Save stupakov/4367456 to your computer and use it in GitHub Desktop.
Save stupakov/4367456 to your computer and use it in GitHub Desktop.
Nacre - Create class for resources, then subclass each resource
module Nacre
module API
class ProductServiceResource # Abstract Class
def self.api
Nacre::Api.global_instance
end
def self.all
search
end
def self.search(params = nil)
results = []
response = nil
begin
response = api.connection.get("#{search_url}#{params}")
rescue
raise "Error in response: #{response.body.inspect}\n#{api.inspect}"
end
hash = JSON.parse response.body
hash['response']['results'].each do |result|
model = self.new(result)
results << model
end
return results
end
private
def self.service_url
"/product-service"
end
def self.url
raise NotImplementedError.new("Child class must implement #{method_name}")
end
def self.search_url
raise NotImplementedError.new("Child class must implement #{method_name}")
end
end
end
end
module Nacre
module API
class Product < ProductServiceResource
@@fields = [ :product_id, :product_name, :sku, :ean, :upc, :isbn,
:stock_tracked, :sales_channel, :created, :updated,
:bp_category, :product_group ]
@@fields.each do |attr|
attr_accessor attr
end
# is this a hash or array of fields??
def initialize(hash = nil)
load_values(hash)
self # is this necessary?
end
private
def self.url
service_url + "/product"
end
def self.search_url
service_url + '/product-search'
end
def fields
@@fields
end
#move this to the parent class
def load_values(hash)
self.fields.each do |field|
self.public_send "#{field.to_s}=", hash[field]
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment