Class: RubyLokaliseApi::Resources::Base

Inherits:
Object
  • Object
show all
Extended by:
RubyLokaliseApi::Request, Utils::AttributeHelpers, Utils::EndpointHelpers
Includes:
Utils::AttributeHelpers
Defined in:
lib/ruby_lokalise_api/resources/base.rb

Constant Summary

Constants included from RubyLokaliseApi::Request

RubyLokaliseApi::Request::PAGINATION_HEADERS

Constants included from Utils::AttributeHelpers

Utils::AttributeHelpers::UNIFIED_RESOURCES

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from BaseRequest

#delete, #get, #patch, #post, #put

Methods included from Connection

#connection

Methods included from JsonHandler

#custom_dump, #custom_load

Methods included from Utils::AttributeHelpers

attributes_for, data_key_for, id_key_for

Methods included from Utils::EndpointHelpers

path_from

Constructor Details

#initialize(response, endpoint_generator = nil) ⇒ RubyLokaliseApi::Resources::Base

Initializes a new resource based on the response. ‘endpoint_generator` is used in cases when a new instance is generated from a different resource. For example, restoring from a snapshot creates a totally different project which should have a new path.

Parameters:

  • response (Hash)
  • endpoint_generator (Proc) (defaults to: nil)

    Generate proper paths for certain resources



23
24
25
26
27
28
# File 'lib/ruby_lokalise_api/resources/base.rb', line 23

def initialize(response, endpoint_generator = nil)
  populate_attributes_for response['content']
  extract_common_attributes_for response['content']
  @client = response['client']
  @path = infer_path_from response, endpoint_generator
end

Instance Attribute Details

#branchObject (readonly)

Returns the value of attribute branch.



13
14
15
# File 'lib/ruby_lokalise_api/resources/base.rb', line 13

def branch
  @branch
end

#clientObject (readonly)

Returns the value of attribute client.



13
14
15
# File 'lib/ruby_lokalise_api/resources/base.rb', line 13

def client
  @client
end

#key_idObject (readonly)

Returns the value of attribute key_id.



13
14
15
# File 'lib/ruby_lokalise_api/resources/base.rb', line 13

def key_id
  @key_id
end

#pathObject (readonly)

Returns the value of attribute path.



13
14
15
# File 'lib/ruby_lokalise_api/resources/base.rb', line 13

def path
  @path
end

#project_idObject (readonly)

Returns the value of attribute project_id.



13
14
15
# File 'lib/ruby_lokalise_api/resources/base.rb', line 13

def project_id
  @project_id
end

#raw_dataObject (readonly)

Returns the value of attribute raw_data.



13
14
15
# File 'lib/ruby_lokalise_api/resources/base.rb', line 13

def raw_data
  @raw_data
end

#team_idObject (readonly)

Returns the value of attribute team_id.



13
14
15
# File 'lib/ruby_lokalise_api/resources/base.rb', line 13

def team_id
  @team_id
end

#user_idObject (readonly)

Returns the value of attribute user_id.



13
14
15
# File 'lib/ruby_lokalise_api/resources/base.rb', line 13

def user_id
  @user_id
end

Class Method Details

.create(client, path, params) ⇒ Object

Creates one or multiple records



86
87
88
89
# File 'lib/ruby_lokalise_api/resources/base.rb', line 86

def create(client, path, params)
  response = post path, client, prepare_params(params)
  object_from response, params
end

.destroy(client, path, params = {}) ⇒ Object

Destroys records by given ids



98
99
100
# File 'lib/ruby_lokalise_api/resources/base.rb', line 98

def destroy(client, path, params = {})
  delete(path, client, prepare_params(params))['content']
end

.find(client, path, params = {}) ⇒ Object

Fetches a single record



81
82
83
# File 'lib/ruby_lokalise_api/resources/base.rb', line 81

def find(client, path, params = {})
  new get(path, client, prepare_params(params))
end

.inherited(subclass) ⇒ Object

Dynamically adds attribute readers for each inherited class. Attributes are defined in the ‘data/attributes.json` file. Also sets the `ATTRIBUTES` constant to assign values to each attribute later when the response arrives from the API



48
49
50
51
52
53
54
55
# File 'lib/ruby_lokalise_api/resources/base.rb', line 48

def inherited(subclass)
  klass_attributes = attributes_for subclass
  subclass.class_exec do
    const_set :ATTRIBUTES, klass_attributes
    attr_reader(*klass_attributes)
  end
  super
end

.supports(*methods) ⇒ Object

Defines CRUD instance methods. In the simplest case it delegates work to the class method. In more complex case it is possible to specify sub-path and the class method name to call. Usage: ‘supports :update, :destroy, [:complex_method, ’/sub/path’, :update]‘



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/ruby_lokalise_api/resources/base.rb', line 61

def supports(*methods)
  methods.each do |m_data|
    # `method_name` - the method that the resource should support
    # `sub_path` - a string that has to be appended to a base path
    # `c_method` - method name to delegate the work to
    method_name, sub_path, c_method =
      m_data.is_a?(Array) ? m_data : [m_data, '', m_data]

    define_method method_name do |params = {}|
      path = instance_variable_get(:@path)
      # If there's a sub_path which is a string,
      # preserve the initial path to allow further chaining
      params = params.merge(_initial_path: path) if sub_path
      self.class.send c_method, instance_variable_get(:@client),
                      path + sub_path, params
    end
  end
end

.update(client, path, params) ⇒ Object

Updates one or multiple records



92
93
94
95
# File 'lib/ruby_lokalise_api/resources/base.rb', line 92

def update(client, path, params)
  response = put path, client, prepare_params(params)
  object_from response, params
end

Instance Method Details

#[](raw_key_attr) ⇒ Object

Returns object attribute with [] notation by calling the corresponding method on the object if the instance variable named after the requested key exists

Parameters:

  • raw_key_attr (String or Hash)


35
36
37
38
39
40
41
# File 'lib/ruby_lokalise_api/resources/base.rb', line 35

def [](raw_key_attr)
  key_attr = raw_key_attr.to_s.to_sym

  return nil unless instance_variables.include?(:"@#{key_attr}")

  send key_attr
end

#extract_common_attributes_for(content) ⇒ Object

Extracts all common attributes that resources have. Some of them may be absent in certain cases. rubocop:disable Naming/MemoizedInstanceVariableName



208
209
210
211
212
213
214
215
216
217
# File 'lib/ruby_lokalise_api/resources/base.rb', line 208

def extract_common_attributes_for(content)
  return unless content

  @raw_data = content
  @project_id ||= content['project_id']
  @user_id ||= content['user_id']
  @team_id ||= content['team_id']
  @key_id ||= content['key_id']
  @branch ||= content['branch']
end

#id_from(response, id_key, data_key) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/ruby_lokalise_api/resources/base.rb', line 174

def id_from(response, id_key, data_key)
  # Content may be `{"project_id": '123', ...}` or {"snapshot": {"snapshot_id": '123', ...}}
  # Sometimes there is an `id_key` but it has a value of `null`
  # (for example when we do not place the actual order but only check its price).
  # In rare cases the actual identifier does not have an "_id" suffix
  # (for segments that have "segment_number" field instead)
  # Therefore we must explicitly check if the key is present
  content = response['content']
  return content[id_key] if content.respond_to?(:key?) && content&.key?(id_key)

  content[data_key][id_key]
end

#infer_path_from(response, endpoint_generator = nil) ⇒ Object

Generates path for the individual resource based on the path for the collection



145
146
147
148
149
150
# File 'lib/ruby_lokalise_api/resources/base.rb', line 145

def infer_path_from(response, endpoint_generator = nil)
  id_key = id_key_for self.class.name.base_class_name
  data_key = data_key_for model_class: self.class.name.base_class_name

  path_with_id response, id_key, data_key, endpoint_generator
end

#path_with_id(response, id_key, data_key, endpoint_generator = nil) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/ruby_lokalise_api/resources/base.rb', line 152

def path_with_id(response, id_key, data_key, endpoint_generator = nil)
  # Some resources do not have ids at all
  return unless response['content'] && (response['content'].key?(id_key) || response['content'].key?(data_key))

  # ID of the resource
  id = id_from response, id_key, data_key

  # If `endpoint_generator` is present, generate a new path
  # based on the fetched id
  if endpoint_generator
    path = endpoint_generator.call project_id, id
    return path.remove_trailing_slash
  end

  path = response['path'] || response['base_path']
  # If path already has id - just return it
  return path if path.match?(/#{id}\z/)

  # Otherwise this looks like a collection path, so append the resource id to it
  path.remove_trailing_slash + "/#{id}"
end

#populate_attributes_for(content) ⇒ Object

Store all resources attributes under the corresponding instance variables. ‘ATTRIBUTES` is defined inside resource-specific classes



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/ruby_lokalise_api/resources/base.rb', line 189

def populate_attributes_for(content)
  return unless content

  data_key = data_key_for model_class: self.class.name.base_class_name

  self.class.const_get(:ATTRIBUTES).each do |attr|
    value = if content.key?(data_key) && content[data_key].is_a?(Hash)
              content[data_key][attr]
            else
              content[attr]
            end

    instance_variable_set "@#{attr}", value
  end
end