base.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. require 'shopify_api/version'
  2. module ShopifyAPI
  3. class Base < ActiveResource::Base
  4. extend Countable
  5. self.include_root_in_json = false
  6. self.headers['User-Agent'] = ["ShopifyAPI/#{ShopifyAPI::VERSION}",
  7. "ActiveResource/#{ActiveResource::VERSION::STRING}",
  8. "Ruby/#{RUBY_VERSION}"].join(' ')
  9. def encode(options = {})
  10. same = dup
  11. same.attributes = {self.class.element_name => same.attributes} if self.class.format.extension == 'json'
  12. same.send("to_#{self.class.format.extension}", options)
  13. end
  14. def as_json(options = nil)
  15. root = options[:root] if options.try(:key?, :root)
  16. if include_root_in_json
  17. root = self.class.model_name.element if root == true
  18. { root => serializable_hash(options) }
  19. else
  20. serializable_hash(options)
  21. end
  22. end
  23. class << self
  24. if ActiveResource::VERSION::MAJOR == 4 && ActiveResource::VERSION::PRE == 'threadsafe'
  25. def headers
  26. if _headers_defined?
  27. _headers
  28. elsif superclass != Object && superclass.headers
  29. superclass.headers
  30. else
  31. _headers ||= {}
  32. end
  33. end
  34. else
  35. def headers
  36. if defined?(@headers)
  37. @headers
  38. elsif superclass != Object && superclass.headers
  39. superclass.headers
  40. else
  41. @headers ||= {}
  42. end
  43. end
  44. end
  45. def activate_session(session)
  46. self.site = session.site
  47. self.headers.merge!('X-Shopify-Access-Token' => session.token)
  48. end
  49. def clear_session
  50. self.site = nil
  51. self.headers.delete('X-Shopify-Access-Token')
  52. end
  53. def init_prefix(resource)
  54. init_prefix_explicit(resource.to_s.pluralize, "#{resource}_id")
  55. end
  56. def init_prefix_explicit(resource_type, resource_id)
  57. self.prefix = "/admin/#{resource_type}/:#{resource_id}/"
  58. define_method resource_id.to_sym do
  59. @prefix_options[resource_id]
  60. end
  61. end
  62. end
  63. def persisted?
  64. !id.nil?
  65. end
  66. private
  67. def only_id
  68. encode(:only => :id, :include => [], :methods => [])
  69. end
  70. end
  71. end