Class: SqlcachedClient::Entity

Inherits:
Object
  • Object
show all
Extended by:
Arel, TreeVisitor
Defined in:
lib/sqlcached_client/entity.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Arel

build_arel

Methods included from TreeVisitor

visit_in_preorder

Constructor Details

#initialize(attributes) ⇒ Entity

Returns a new instance of Entity.

Parameters:

  • attributes (Hash)


14
15
16
17
# File 'lib/sqlcached_client/entity.rb', line 14

def initialize(attributes)
  @attributes = attributes
  define_readers(attributes.keys)
end

Class Attribute Details

.query_idObject (readonly)

Returns the value of attribute query_id.



21
22
23
# File 'lib/sqlcached_client/entity.rb', line 21

def query_id
  @query_id
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



11
12
13
# File 'lib/sqlcached_client/entity.rb', line 11

def attributes
  @attributes
end

Class Method Details

.association_namesObject



181
182
183
# File 'lib/sqlcached_client/entity.rb', line 181

def association_names
  registered_associations.map(&:accessor_name)
end

.build_query_treeObject



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/sqlcached_client/entity.rb', line 207

def build_query_tree
  # returns the subtrees (associated classes) of the given entity class
  get_associated_entities = -> (entity) {
    entity.registered_associations.map do |a|
      Module.const_get(a.class_name)
    end
  }

  # function to apply to each node while traversing the tree
  visit = -> (entity, parent, index) {
    entity.server.build_request_item(
      entity.query_id,
      entity.query,
      # query_params
      if parent
        Hash[
          parent.registered_associations[index].join_attributes.map do |j_attr|
            [ j_attr[0], {
              value: j_attr[1],
              type:
                if entity.join_constant_value?(j_attr[1])
                  'constant'
                else
                  'parent_attribute'
                end
            } ]
          end
        ]
      else
        nil
      end,
      entity.cache
    ).merge(associations: entity.association_names)
  }

  # builds the result of a visit step
  result_builder = -> (root, subtrees) {
    { root: root, subtrees: subtrees }
  }

  # traverse the tree
  visit_in_preorder(get_associated_entities, visit, result_builder)
end

.cache(seconds = nil) ⇒ Object

Configures the caching timing if a parameter is provided, otherwise returns the value set in the current class or in a superclass. Default value is true.



193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/sqlcached_client/entity.rb', line 193

def cache(seconds = nil)
  if seconds.nil?
    @cache ||
      if superclass = ancestors[1..-1].detect { |a| a.respond_to?(:cache) }
        superclass.cache
      else
        true
      end
  else
    @cache = seconds
  end
end

.entity_name(value) ⇒ Object

Sets the name of this entity



24
25
26
# File 'lib/sqlcached_client/entity.rb', line 24

def entity_name(value)
  @query_id = value
end

.has_many(accessor_name, options) ⇒ Object

Defines a ‘has_many’ relationship. Available options are

class_name

Specifies the class of the associated objects, if not given it’s inferred from the accessor_name (singularized + camelized).

where

Specifies how to fill the query template for the associated objects. It’s an hash where each key is a foreign parameter that will be set to the value provided. A special case occours when the value is a Symbol, in this case it represents the value of the attribute named as the symbol. For example, where: { id: :user_id } fills the parameter id of the foreign entity with the value of self.user_id.



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
# File 'lib/sqlcached_client/entity.rb', line 114

def has_many(accessor_name, options)
  foreign_class_name =
    if options[:class_name].present?
      options[:class_name]
    else
      accessor_name.to_s.singularize.camelize
    end
  # the query to run to get the data
  association = -> (this, foreign_entity, join_attributes, dry_run) {
    foreign_entity.where(Hash[ join_attributes.map do |attr_names|
      attr_value =
        if this.join_constant_value?(attr_names[1])
          attr_names[1]
        else
          this.send(attr_names[1])
        end
      [ attr_names[0], attr_value ]
    end ], dry_run)
  }
  # get the attributes to define the foreign scope
  join_attributes = (options[:where] || []).to_a
  # memoize the associated resultset
  memoize_var = "@has_many_#{accessor_name}"
  # define the accessor method
  define_method(accessor_name) do |dry_run = false|
    # get the associated entity class
    foreign_entity = Module.const_get(foreign_class_name)
    if dry_run
      association.(self, foreign_entity, join_attributes, true)
    else
      instance_variable_get(memoize_var) ||
        instance_variable_set(memoize_var,
          association.(self, foreign_entity, join_attributes, false))
    end
  end
  # define the setter method
  define_method("#{accessor_name}=") do |array|
    # get the associated entity class
    foreign_entity = Module.const_get(foreign_class_name)
    instance_variable_set(memoize_var,
      Resultset.new(foreign_entity, array))
  end
  # save the newly created association
  register_association(OpenStruct.new({
    accessor_name: accessor_name.to_sym,
    class_name: foreign_class_name,
    join_attributes: join_attributes
  }))
end

.has_one(accessor_name, options) ⇒ Object

Defines a ‘has_one’ relationship. See ‘has_many’ for the available options



166
167
168
169
170
171
172
173
# File 'lib/sqlcached_client/entity.rb', line 166

def has_one(accessor_name, options)
  plural_accessor_name = "s_#{accessor_name}".to_s.pluralize
  class_name = accessor_name.to_s.camelize
  has_many(plural_accessor_name, { class_name: class_name }.merge(options))
  define_method(accessor_name) do
    send(plural_accessor_name).first
  end
end

.is_an_association?(name) ⇒ Boolean

Returns:

  • (Boolean)


186
187
188
# File 'lib/sqlcached_client/entity.rb', line 186

def is_an_association?(name)
  association_names.include?(name.to_sym)
end

.join_constant_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


252
253
254
# File 'lib/sqlcached_client/entity.rb', line 252

def join_constant_value?(value)
  !value.is_a?(Symbol)
end

.load_tree(root_conditions) ⇒ Object

Like ‘where’ but loads every associated entity recursively at any level,

with only one interaction with the server

Parameters:

  • root_conditions (Array)


259
260
261
262
263
264
265
266
267
268
269
# File 'lib/sqlcached_client/entity.rb', line 259

def load_tree(root_conditions)
  server.session do |server, session|
    Resultset.new(
      self,
      server.run_query(
        session,
        server.build_tree_request(build_query_tree, root_conditions)
      )
    )
  end
end

.query(*args, &block) ⇒ Object

Sets the query of this entity if a parameter is provided, otherwise returns the value previously set.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/sqlcached_client/entity.rb', line 30

def query(*args, &block)
  if args.empty?
    @query
  else
    if args[0].is_a?(String)
      @query = args[0].strip
    else
      @query = build_arel(
        args.inject({}) do |acc, param|
          acc.merge(
            param.is_a?(Hash) ? param : Hash[ [[param, nil]] ]
          )
        end,
        block).to_sql
    end
  end
end

.registered_associationsObject



176
177
178
# File 'lib/sqlcached_client/entity.rb', line 176

def registered_associations
  @registered_associations || []
end

.server(config = nil) ⇒ Object

Configures the server of this entity if a parameter is provided, otherwise returns the server object previously set.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/sqlcached_client/entity.rb', line 50

def server(config = nil)
  if config.nil?
    @server ||
      if superclass = ancestors[1..-1].detect { |a| a.respond_to?(:server) }
        superclass.server
      else
        nil
      end
  else
    @server =
      if config.is_a?(Hash)
        Server.new(config)
      else
        config
      end
  end
end

.server_session(&block) ⇒ Object

Gets a session from the server and yields the passed block



69
70
71
# File 'lib/sqlcached_client/entity.rb', line 69

def server_session(&block)
  server.session(&block)
end

.where(params, dry_run = false) ⇒ Resultset

Runs the entity query with the provided parameters

Returns:



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/sqlcached_client/entity.rb', line 75

def where(params, dry_run = false)
  request =
    begin
      paramIterator = -> (parameter) {
        server.build_request_item(query_id, query, parameter, cache)
      }
      if params.is_a?(Array)
        params.map { |p| instance_exec(p, &paramIterator) }
      else
        instance_exec(params, &paramIterator)
      end
    end
  if dry_run
    request
  else
    data =
      server.session do |server, session|
        server.run_query(session, server.build_request(
          request.is_a?(Array) ? request : [request]
        ))
      end
    data.flatten!(1) if data.is_a?(Array)
    Resultset.new(self, data)
  end
end

Instance Method Details

#build_associations(max_depth = false) ⇒ Object



330
331
332
# File 'lib/sqlcached_client/entity.rb', line 330

def build_associations(max_depth = false)
  Resultset.new(self.class, [self]).build_associations(max_depth)
end

#define_readers(attr_names) ⇒ Object

Define the readers for the attribute names specified

Parameters:

  • attr_names (Array)


281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/sqlcached_client/entity.rb', line 281

def define_readers(attr_names)
  attr_names.each do |attr_name|
    if respond_to?(attr_name)
      if self.class.is_an_association?(attr_name)
        # lazy instantiate associated records
        association_writer = method("#{attr_name}=")
        association_reader = method(attr_name)
        define_singleton_method(attr_name) do
          association_writer.(attributes[attr_name])
          association_reader.()
        end
      else
        raise "Cannot define accessor: #{attr_name}"
      end
    else
      define_singleton_method(attr_name) do
        attributes[attr_name]
      end
    end
  end
end

#get_association_requestsObject



309
310
311
312
313
# File 'lib/sqlcached_client/entity.rb', line 309

def get_association_requests
  self.class.association_names.map do |a_name|
    send(a_name, true)
  end
end

#get_associationsObject



323
324
325
326
327
# File 'lib/sqlcached_client/entity.rb', line 323

def get_associations
  self.class.association_names.map do |a_name|
    send(a_name)
  end
end

#join_constant_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


304
305
306
# File 'lib/sqlcached_client/entity.rb', line 304

def join_constant_value?(value)
  self.class.join_constant_value?(value)
end

#set_associations_data(associations_data) ⇒ Object



316
317
318
319
320
# File 'lib/sqlcached_client/entity.rb', line 316

def set_associations_data(associations_data)
  self.class.association_names.map.with_index do |a_name, i|
    send("#{a_name}=", associations_data[i])
  end
end

#to_hObject



335
336
337
# File 'lib/sqlcached_client/entity.rb', line 335

def to_h
  attributes
end