Class: ShopifyAPI::Rest::Base

Inherits:
Object
  • Object
show all
Extended by:
T::Helpers, T::Sig
Defined in:
lib/shopify_api/rest/base.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(session: nil, from_hash: nil) ⇒ Base

Returns a new instance of Base.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/shopify_api/rest/base.rb', line 33

def initialize(session: nil, from_hash: nil)
  @original_state = T.let({}, T::Hash[Symbol, T.untyped])
  @custom_prefix = T.let(nil, T.nilable(String))
  @forced_nils = T.let({}, T::Hash[String, T::Boolean])
  @aliased_properties = T.let({}, T::Hash[String, String])

  session ||= ShopifyAPI::Context.active_session

  client = ShopifyAPI::Clients::Rest::Admin.new(session: session)

  @session = T.let(T.must(session), Auth::Session)
  @client = T.let(client, Clients::Rest::Admin)
  @errors = T.let(Rest::BaseErrors.new, Rest::BaseErrors)

  from_hash&.each do |key, value|
    set_property(key, value)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth_id, val = nil) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/shopify_api/rest/base.rb', line 243

def method_missing(meth_id, val = nil)
  match = meth_id.id2name.match(/([^=]+)(=)?/)

  var = T.must(T.must(match)[1])

  if T.must(match)[2]
    set_property(var, val)
    @forced_nils[var] = val.nil?
  else
    get_property(var)
  end
end

Class Attribute Details

.custom_prefixObject (readonly)

Returns the value of attribute custom_prefix.



56
57
58
# File 'lib/shopify_api/rest/base.rb', line 56

def custom_prefix
  @custom_prefix
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



25
26
27
# File 'lib/shopify_api/rest/base.rb', line 25

def errors
  @errors
end

#original_stateObject

Returns the value of attribute original_state.



22
23
24
# File 'lib/shopify_api/rest/base.rb', line 22

def original_state
  @original_state
end

Class Method Details

.base_find(session: nil, ids: {}, params: {}) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/shopify_api/rest/base.rb', line 65

def base_find(session: nil, ids: {}, params: {})
  session ||= ShopifyAPI::Context.active_session

  client = ShopifyAPI::Clients::Rest::Admin.new(session: session)

  path = T.must(get_path(http_method: :get, operation: :get, ids: ids))
  response = client.get(path: path, query: params.compact)

  instance_variable_get(:"@prev_page_info").value = response.prev_page_info
  instance_variable_get(:"@next_page_info").value = response.next_page_info

  create_instances_from_response(response: response, session: T.must(session))
end

.class_nameObject



80
81
82
# File 'lib/shopify_api/rest/base.rb', line 80

def class_name
  T.must(name).demodulize.underscore
end

.create_instance(data:, session:, instance: nil) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/shopify_api/rest/base.rb', line 216

def create_instance(data:, session:, instance: nil)
  instance ||= new(session: session)
  instance.original_state = {}

  data.each do |attribute, value|
    attr_sym = attribute.to_sym

    if has_many?(attr_sym) && value
      attr_list = []
      value.each do |element|
        attr_list << T.unsafe(@has_many[attr_sym]).create_instance(data: element, session: session)
      end
      instance.public_send("#{attribute}=", attr_list)
    elsif has_one?(attr_sym) && value
      instance.public_send("#{attribute}=",
        T.unsafe(@has_one[attr_sym]).create_instance(data: value, session: session))
    else
      instance.public_send("#{attribute}=", value)
      instance.original_state[attr_sym] = value
    end
  end

  instance
end

.create_instances_from_response(response:, session:) ⇒ Object



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/shopify_api/rest/base.rb', line 197

def create_instances_from_response(response:, session:)
  objects = []

  body = T.cast(response.body, T::Hash[String, T.untyped])

  if body.key?(class_name.pluralize) || (body.key?(class_name) && body[class_name].is_a?(Array))
    (body[class_name.pluralize] || body[class_name]).each do |entry|
      objects << create_instance(data: entry, session: session)
    end
  elsif body.key?(class_name)
    objects << create_instance(data: body[class_name], session: session)
  end

  objects
end

.get_path(http_method:, operation:, entity: nil, ids: {}) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/shopify_api/rest/base.rb', line 137

def get_path(http_method:, operation:, entity: nil, ids: {})
  match = T.let(nil, T.nilable(String))
  max_ids = T.let(-1, Integer)
  @paths.each do |path|
    next if http_method != path[:http_method] || operation != path[:operation]

    path_ids = T.cast(path[:ids], T::Array[Symbol])

    url_ids = ids.transform_keys(&:to_sym)
    path_ids.each do |id|
      if url_ids[id].nil? && (entity_id = entity&.public_send(id))
        url_ids[id] = entity_id
      end
    end

    url_ids.compact!

    # We haven't found all the required ids or we have a more specific match
    next if !(path_ids - url_ids.keys).empty? || path_ids.length <= max_ids

    max_ids = path_ids.length
    match = T.cast(path[:path], String).gsub(/(<([^>]+)>)/) do
      url_ids[T.unsafe(Regexp.last_match)[2].to_sym]
    end
  end

  custom_prefix ? "#{T.must(custom_prefix).sub(%r{\A/}, "")}/#{match}" : match
end

.has_many?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


115
116
117
# File 'lib/shopify_api/rest/base.rb', line 115

def has_many?(attribute)
  @has_many.include?(attribute)
end

.has_one?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


120
121
122
# File 'lib/shopify_api/rest/base.rb', line 120

def has_one?(attribute)
  @has_one.include?(attribute)
end

.json_body_nameObject



90
91
92
# File 'lib/shopify_api/rest/base.rb', line 90

def json_body_name
  class_name.underscore
end

.next_page?Boolean

Returns:

  • (Boolean)


110
111
112
# File 'lib/shopify_api/rest/base.rb', line 110

def next_page?
  !instance_variable_get(:"@next_page_info").value.nil?
end

.next_page_infoObject



100
101
102
# File 'lib/shopify_api/rest/base.rb', line 100

def next_page_info
  instance_variable_get(:"@next_page_info").value
end

.prev_page?Boolean

Returns:

  • (Boolean)


105
106
107
# File 'lib/shopify_api/rest/base.rb', line 105

def prev_page?
  !instance_variable_get(:"@prev_page_info").value.nil?
end

.prev_page_infoObject



95
96
97
# File 'lib/shopify_api/rest/base.rb', line 95

def prev_page_info
  instance_variable_get(:"@prev_page_info").value
end

.primary_keyObject



85
86
87
# File 'lib/shopify_api/rest/base.rb', line 85

def primary_key
  "id"
end

.read_only_attributesObject



125
126
127
# File 'lib/shopify_api/rest/base.rb', line 125

def read_only_attributes
  @read_only_attributes&.map { |a| :"@#{a}" }
end

.request(http_method:, operation:, session:, ids: {}, params: {}, body: nil, entity: nil) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/shopify_api/rest/base.rb', line 177

def request(http_method:, operation:, session:, ids: {}, params: {}, body: nil, entity: nil)
  client = ShopifyAPI::Clients::Rest::Admin.new(session: session)

  path = get_path(http_method: http_method, operation: operation.to_sym, ids: ids)

  case http_method
  when :get
    client.get(path: T.must(path), query: params.compact)
  when :post
    client.post(path: T.must(path), query: params.compact, body: body || {})
  when :put
    client.put(path: T.must(path), query: params.compact, body: body || {})
  when :delete
    client.delete(path: T.must(path), query: params.compact)
  else
    raise Errors::InvalidHttpRequestError, "Invalid HTTP method: #{http_method}"
  end
end

Instance Method Details

#delete(params: {}) ⇒ Object



299
300
301
302
303
304
305
306
307
# File 'lib/shopify_api/rest/base.rb', line 299

def delete(params: {})
  @client.delete(
    path: T.must(self.class.get_path(http_method: :delete, operation: :delete, entity: self)),
    query: params.compact
  )
rescue ShopifyAPI::Errors::HttpResponseError => e
  @errors.errors << e
  raise
end

#respond_to_missing?(meth_id, *args) ⇒ Boolean

Returns:

  • (Boolean)


257
258
259
260
261
262
# File 'lib/shopify_api/rest/base.rb', line 257

def respond_to_missing?(meth_id, *args)
  str = meth_id.id2name
  match = str.match(/([^=]+)=/)

  match.nil? ? true : super
end

#save(update_object: false) ⇒ Object



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/shopify_api/rest/base.rb', line 315

def save(update_object: false)
  hash = HashDiff::Comparison.new(original_state, to_hash).left_diff
  method = hash[self.class.primary_key] ? :put : :post

  path = self.class.get_path(http_method: method, operation: method, entity: self)
  if path.nil?
    method = method == :post ? :put : :post
    path = self.class.get_path(http_method: method, operation: method, entity: self)
  end

  response = @client.public_send(method, body: { self.class.json_body_name => hash }, path: path)

  if update_object
    self.class.create_instance(
      data: response.body[self.class.class_name.downcase],
      session: @session, instance: self
    )
  end
rescue ShopifyAPI::Errors::HttpResponseError => e
  @errors.errors << e
  raise
end

#save!Object



310
311
312
# File 'lib/shopify_api/rest/base.rb', line 310

def save!
  save(update_object: true)
end

#to_hashObject



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# File 'lib/shopify_api/rest/base.rb', line 265

def to_hash
  hash = {}
  instance_variables.each do |var|
    next if [
      :"@original_state",
      :"@session",
      :"@client",
      :"@forced_nils",
      :"@errors",
      :"@aliased_properties",
    ].include?(var)
    next if self.class.read_only_attributes&.include?(var)

    var = var.to_s.delete("@")
    attribute = if @aliased_properties.value?(var)
      T.must(@aliased_properties.key(var))
    else
      var
    end.to_sym

    if self.class.has_many?(attribute)
      hash[attribute.to_s] = get_property(attribute).map(&:to_hash).to_a if get_property(attribute)
    elsif self.class.has_one?(attribute)
      element_hash = get_property(attribute)&.to_hash
      hash[attribute.to_s] = element_hash if element_hash || @forced_nils[attribute.to_s]
    elsif !get_property(attribute).nil? || @forced_nils[attribute.to_s]
      hash[attribute.to_s] =
        get_property(attribute)
    end
  end
  hash
end