Module: Clayful

Defined in:
lib/clayful.rb,
lib/response.rb,
lib/exception.rb,
lib/requester.rb,
lib/models/cart.rb,
lib/models/brand.rb,
lib/models/group.rb,
lib/models/image.rb,
lib/models/order.rb,
lib/models/store.rb,
lib/models/coupon.rb,
lib/models/review.rb,
lib/models/vendor.rb,
lib/models/catalog.rb,
lib/models/country.rb,
lib/models/product.rb,
lib/models/currency.rb,
lib/models/customer.rb,
lib/models/discount.rb,
lib/models/order_tag.rb,
lib/models/wish_list.rb,
lib/models/collection.rb,
lib/models/downloadable.rb,
lib/models/subscription.rb,
lib/models/tax_category.rb,
lib/models/payment_method.rb,
lib/models/review_comment.rb,
lib/models/shipping_method.rb,
lib/models/shipping_policy.rb,
lib/models/subscription_plan.rb

Defined Under Namespace

Classes: Brand, Cart, Catalog, Collection, Country, Coupon, Currency, Customer, Discount, Downloadable, Exception, Group, Image, Order, OrderTag, PaymentMethod, Product, Requester, Response, Review, ReviewComment, ShippingMethod, ShippingPolicy, Store, Subscription, SubscriptionPlan, TaxCategory, Vendor, WishList

Constant Summary collapse

@@base_url =
'https://api.clayful.io'
@@default_headers =
{
	'Accept-Encoding' => '*',
	'User-Agent'      => 'clayful-ruby',
	'Clayful-SDK'     => 'clayful-ruby'
}
@@plugins =
{
	'request' => Clayful::Requester.request
}
@@listeners =
{
	'request'  => [],
	'response' => []
}

Class Method Summary collapse

Class Method Details

.base_urlObject



26
# File 'lib/clayful.rb', line 26

def self.base_url; @@base_url end

.base_url=(v) ⇒ Object



27
# File 'lib/clayful.rb', line 27

def self.base_url=v; @@base_url = v end

.call_api(options) ⇒ Object



132
133
134
135
136
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
165
166
167
168
169
170
# File 'lib/clayful.rb', line 132

def self.call_api(options)

	extracted = self.extract_request_arguments(options)

	extracted = extracted.merge({
		'request_url'    => self.get_endpoint(extracted['request_url']),
		'model_name'     => options['model_name'],
		'method_name'    => options['method_name'],
		'uses_form_data' => !!options['uses_form_data'],
		'error'          => nil,
		'response'       => nil,
	})

	# Extend default headers with header options
	extracted['headers'] = @@default_headers.clone.merge(extracted['headers'])

	self.trigger('request', extracted)

	begin

		response = self.plugins['request'].call(extracted)

		extracted['response'] = response

		self.trigger('response', extracted)

		return response

	rescue Clayful::Exception => e

		extracted['error'] = e

		self.trigger('response', extracted)

		raise # re-raise the error

	end

end

.config(options = {}) ⇒ Object



173
174
175
176
177
178
179
# File 'lib/clayful.rb', line 173

def self.config(options = {})

	headers = self.options_to_headers(options)

	@@default_headers = @@default_headers.merge(headers)

end

.default_headersObject



29
# File 'lib/clayful.rb', line 29

def self.default_headers; @@default_headers end

.default_headers=(v) ⇒ Object



30
# File 'lib/clayful.rb', line 30

def self.default_headers=v; @@default_headers = v end

.extract_request_arguments(options = {}) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/clayful.rb', line 94

def self.extract_request_arguments(options = {})

	result = {
		'http_method' => options['http_method'],
		'request_url' => options['path'],
		'payload'     => nil,
		'query'       => {},
		'headers'     => {},
		'meta'        => {}
	}

	rest = options['args'].slice(options['params'].length..-1)

	options['params'].each.with_index do |key, i|

		result['request_url'] = result['request_url'].sub('{' + key + '}', options['args'][i].to_s)
	end

	http_method = options['http_method']

	if (http_method == 'POST' or http_method == 'PUT') and (not options['without_payload'])

		result['payload'] = rest.shift
	end

	query_headers = rest[0] ? rest[0] : {}
	query = query_headers.fetch('query', {})
	meta = query_headers.fetch('meta', {})

	result['query'] = self.normalize_query_values(query)
	result['headers'] = self.options_to_headers(query_headers)
	result['meta'] = meta

	result

end

.format_image_url(base_url, options = {}) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/clayful.rb', line 231

def self.format_image_url(base_url, options = {})

	query = []

	normalized = self.normalize_query_values(options)

	normalized.each do |k, v|
		query.push("#{k}=#{v}")
	end

	query = query.join('&')

	query.empty? ? base_url : base_url + '?' + query

end

.format_number(number, currency = {}) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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
# File 'lib/clayful.rb', line 248

def self.format_number(number, currency = {})

	if not number.is_a? Numeric

		return ''
	end

	precision = currency.fetch('precision', nil)
	delimiter = currency.fetch('delimiter', {})
	thousands = delimiter.fetch('thousands', '')
	decimal = delimiter.fetch('decimal', '.')

	if precision.is_a? Numeric

		# Conver to float to keep '.n'
		n = (10 ** precision).to_f

		number = (number * n).round / n

		# To deal with 0.0 case..
		if precision == 0

			number = number.round
		end

	end

	a, b = number.to_s.split('.')

	a = a.reverse.scan(/.{1,3}/).join(thousands).reverse
	b = b ? b : ''

	if precision.is_a? Numeric

		diff = precision - b.length
		diff = diff < 0 ? 0 : diff

		b += '0' * diff

	end

	decimal = b.empty? ? '' : decimal

	[a, b].join(decimal)

end

.format_price(number, currency = {}) ⇒ Object



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/clayful.rb', line 296

def self.format_price(number, currency = {})

	formatted_number = self.format_number(number, currency)

	if formatted_number.empty?

		return ''
	end

	symbol = currency.fetch('symbol', '')
	format_string = currency.fetch('format', '{price}')

	format_string
		.sub('{symbol}', symbol)
		.sub('{price}', formatted_number)

end

.get_endpoint(path) ⇒ Object



80
81
82
83
84
# File 'lib/clayful.rb', line 80

def self.get_endpoint(path)

	@@base_url + path

end

.install(scope, plugin) ⇒ Object



182
183
184
185
186
187
188
189
# File 'lib/clayful.rb', line 182

def self.install(scope, plugin)

	if @@plugins[scope]

		@@plugins[scope] = plugin
	end

end

.listenersObject



35
# File 'lib/clayful.rb', line 35

def self.listeners; @@listeners end

.listeners=(v) ⇒ Object



36
# File 'lib/clayful.rb', line 36

def self.listeners=v; @@listeners = v end

.normalize_query_values(query = {}) ⇒ Object



87
88
89
90
91
# File 'lib/clayful.rb', line 87

def self.normalize_query_values(query = {})

	Hash[ query.map { |k, v| [k.to_s, ERB::Util.url_encode(v.to_s)] } ]

end

.off(event_name, callback) ⇒ Object



204
205
206
207
208
209
210
211
212
213
# File 'lib/clayful.rb', line 204

def self.off(event_name, callback)

	listeners = @@listeners[event_name]

	if listeners

		listeners.delete(callback)
	end

end

.on(event_name, callback) ⇒ Object



192
193
194
195
196
197
198
199
200
201
# File 'lib/clayful.rb', line 192

def self.on(event_name, callback)

	listeners = @@listeners[event_name]

	if listeners

		listeners.push(callback)
	end

end

.options_to_headers(o = {}) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/clayful.rb', line 39

def self.options_to_headers(o = {})

	headers = {}

	if o['language']
		headers['Accept-Language'] = o['language']
	end

	if o['currency']
		headers['Accept-Currency'] = o['currency']
	end

	if o['time_zone']
		headers['Accept-Time-Zone'] = o['time_zone']
	end

	if o['client']
		headers['Authorization'] = 'Bearer ' + o['client']
	end

	if o['customer']
		headers['Authorization-Customer'] = o['customer']
	end

	if o['reCAPTCHA']
		headers['reCAPTCHA-Response'] = o['reCAPTCHA']
	end

	if o['debug_language']
		headers['Accept-Debug-Language'] = o['debug_language']
	end

	if o['headers']
		headers = headers.merge(o['headers'])
	end

	headers

end

.pluginsObject



32
# File 'lib/clayful.rb', line 32

def self.plugins; @@plugins end

.plugins=(v) ⇒ Object



33
# File 'lib/clayful.rb', line 33

def self.plugins=v; @@plugins = v end

.trigger(event_name, data) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/clayful.rb', line 216

def self.trigger(event_name, data)

	listeners = @@listeners[event_name]

	if listeners

		listeners.each do |listener|

			listener.call(data)
		end
	end

end