Browse Source

Added Metafields class to API

Julie Hache 15 years ago
parent
commit
c7515548d7
2 changed files with 49 additions and 0 deletions
  1. 1 0
      CHANGELOG
  2. 48 0
      lib/shopify_api.rb

+ 1 - 0
CHANGELOG

@@ -1,3 +1,4 @@
+  - Add metafields
   - Add latest changes from Shopify including asset support, token validation and a common base class
 
 1.0.0

+ 48 - 0
lib/shopify_api.rb

@@ -2,6 +2,7 @@ require 'active_resource'
 require 'digest/md5'
 
 module ShopifyAPI
+  METAFIELD_ENABLED_CLASSES = %w( Order Product CustomCollection SmartCollection Page Blog Article )
 
   module Countable
     def count(options = {})
@@ -9,6 +10,23 @@ module ShopifyAPI
     end
   end
   
+  module Metafields
+     def metafields
+       Metafield.find(:all, :params => {:resource => self.class.collection_name, :resource_id => id})
+     end
+
+     def add_metafield(metafield)
+       raise ArgumentError, "You can only add metafields to resource that has been saved" if new?
+
+       metafield.prefix_options = {
+         :resource => self.class.collection_name,
+         :resource_id => id
+       }
+       metafield.save
+       metafield
+     end
+   end
+  
   # 
   #  The Shopify API authenticates each call via HTTP Authentication, using
   #    * the application's API key as the username, and
@@ -164,6 +182,16 @@ module ShopifyAPI
     def self.current
       find(:one, :from => "/admin/shop.xml")
     end
+    
+    def metafields
+      Metafield.find(:all)
+    end
+    
+    def add_metafield(metafield)
+      raise ArgumentError, "You can only add metafields to resource that has been saved" if new?      
+      metafield.save
+      metafield
+    end
   end               
 
   # Custom collection
@@ -299,6 +327,21 @@ module ShopifyAPI
   class Article < Base
     self.prefix = "/admin/blogs/:blog_id/"
   end
+  
+  class Metafield < Base
+     self.prefix = "/admin/:resource/:resource_id/"
+
+     # Hack to allow both Shop and other Metafields in through the same AR class
+     def self.prefix(options={})
+       options[:resource].nil? ? "/admin/" : "/admin/#{options[:resource]}/#{options[:resource_id]}/"
+     end
+
+     def value
+       return if attributes["value"].nil?
+       attributes["value_type"] == "integer" ? attributes["value"].to_i : attributes["value"]
+     end
+
+   end
 
   class Comment < Base 
     def remove; load_attributes_from_response(post(:remove)); end
@@ -412,4 +455,9 @@ module ShopifyAPI
 
   class ApplicationCharge < Base
   end
+  
+  # Include Metafields module in all enabled classes
+  METAFIELD_ENABLED_CLASSES.each do |klass|
+    "ShopifyAPI::#{klass}".constantize.send(:include, Metafields)
+  end
 end