Class: Retailigence::Model
- Inherits:
-
Object
- Object
- Retailigence::Model
- Defined in:
- lib/retailigence/model.rb
Overview
The base for all API requests and models throughout the Retailigence library.
Class Attribute Summary collapse
-
.safe_attributes ⇒ Object
Attributes safe for initialization.
Class Method Summary collapse
-
.attributes(*attrs) ⇒ Object
Creates a list of safe attributes for assign using #initialize.
-
.get(action = nil, params = {}) ⇒ Object
Convenience method for performing a GET request.
-
.request(method = :get, action = nil, params = {}) ⇒ Object
Perform a request using Typhoeus.
-
.underscore(word) ⇒ Object
Convert the camelCase to its underscore/snake_case equivalent.
Instance Method Summary collapse
-
#initialize(params = {}) ⇒ Model
constructor
Initialize an object with the provided
params.
Constructor Details
#initialize(params = {}) ⇒ Model
Initialize an object with the provided params. For the available params, see the model’s Attributes.
9 10 11 12 13 14 |
# File 'lib/retailigence/model.rb', line 9 def initialize(params = {}) params.each do |key, value| mapped_key = underscore(key) send("#{mapped_key}=".to_sym, value) if safe_attribute?(mapped_key) end end |
Class Attribute Details
.safe_attributes ⇒ Object
Attributes safe for initialization
18 19 20 |
# File 'lib/retailigence/model.rb', line 18 def safe_attributes @safe_attributes end |
Class Method Details
.attributes(*attrs) ⇒ Object
Creates a list of safe attributes for assign using #initialize.
21 22 23 24 25 26 27 28 29 30 |
# File 'lib/retailigence/model.rb', line 21 def attributes(*attrs) @safe_attributes ||= [] attrs.each do |attr_name| name = underscore(attr_name.to_s).to_sym attr_accessor name @safe_attributes << name end end |
.get(action = nil, params = {}) ⇒ Object
Convenience method for performing a GET request. See #request
49 50 51 |
# File 'lib/retailigence/model.rb', line 49 def get(action = nil, params = {}) request(:get, action, params) end |
.request(method = :get, action = nil, params = {}) ⇒ Object
Perform a request using Typhoeus.
Arguments
-
method- Symbol for the request method. -
action- The path to request -
params- Hash of params to send with the request
38 39 40 41 42 43 44 45 46 |
# File 'lib/retailigence/model.rb', line 38 def request(method = :get, action = nil, params = {}) params[:apikey] = Retailigence.configuration.api_key params[:format] = 'JSON' url = "http://#{host}/v#{Retailigence::API_VERSION}/#{action}" response = Typhoeus.send(method, url, params: params) JSON.parse response.body end |
.underscore(word) ⇒ Object
Convert the camelCase to its underscore/snake_case equivalent.
54 55 56 57 58 |
# File 'lib/retailigence/model.rb', line 54 def underscore(word) word.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .tr('-', '_').downcase end |