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


249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/shopify_api/rest/base.rb', line 249

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

.has_manyObject (readonly)

Returns the value of attribute has_many.


59
60
61
# File 'lib/shopify_api/rest/base.rb', line 59

def has_many
  @has_many
end

.has_oneObject (readonly)

Returns the value of attribute has_one.


62
63
64
# File 'lib/shopify_api/rest/base.rb', line 62

def has_one
  @has_one
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


71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/shopify_api/rest/base.rb', line 71

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


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

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

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


222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/shopify_api/rest/base.rb', line 222

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


203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/shopify_api/rest/base.rb', line 203

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


143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/shopify_api/rest/base.rb', line 143

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)

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

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

.has_one?(attribute) ⇒ Boolean

Returns:

  • (Boolean)

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

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

.json_body_nameObject


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

def json_body_name
  class_name.underscore
end

.next_page?Boolean

Returns:

  • (Boolean)

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

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

.next_page_infoObject


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

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

.prev_page?Boolean

Returns:

  • (Boolean)

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

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

.prev_page_infoObject


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

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

.primary_keyObject


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

def primary_key
  "id"
end

.read_only_attributesObject


131
132
133
# File 'lib/shopify_api/rest/base.rb', line 131

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

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


183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/shopify_api/rest/base.rb', line 183

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


312
313
314
315
316
317
318
319
320
# File 'lib/shopify_api/rest/base.rb', line 312

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)

263
264
265
266
267
268
# File 'lib/shopify_api/rest/base.rb', line 263

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

  match.nil? ? true : super
end

#save(update_object: false) ⇒ Object


328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/shopify_api/rest/base.rb', line 328

def save(update_object: false)
  hash = HashDiff::Comparison.new(original_state, to_hash(true)).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


323
324
325
# File 'lib/shopify_api/rest/base.rb', line 323

def save!
  save(update_object: true)
end

#to_hash(saving = false) ⇒ Object


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
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/shopify_api/rest/base.rb', line 271

def to_hash(saving = false)
  hash = {}
  instance_variables.each do |var|
    next if [
      :"@original_state",
      :"@session",
      :"@client",
      :"@forced_nils",
      :"@errors",
      :"@aliased_properties",
    ].include?(var)
    next if saving && 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)
      attribute_class = self.class.has_many[attribute]
      hash[attribute.to_s] = get_property(attribute).map do |element|
        get_element_hash(element, T.unsafe(attribute_class), saving)
      end.to_a if get_property(attribute)
    elsif self.class.has_one?(attribute)
      element_hash = get_element_hash(
        get_property(attribute),
        T.unsafe(self.class.has_one[attribute]),
        saving
      )
      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