Class: SqlcachedClient::Entity

Inherits:
Object
  • Object
show all
Extended by:
Arel
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

Constructor Details

#initialize(attributes) ⇒ Entity

Returns a new instance of Entity.

Parameters:

  • attributes (Hash)


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

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

Class Attribute Details

.query_idObject (readonly)

Returns the value of attribute query_id.



19
20
21
# File 'lib/sqlcached_client/entity.rb', line 19

def query_id
  @query_id
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



9
10
11
# File 'lib/sqlcached_client/entity.rb', line 9

def attributes
  @attributes
end

Class Method Details

.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

.define_readers(attr_names) ⇒ Object

Define the readers for the attribute names specified

Parameters:

  • attr_names (Array)


175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/sqlcached_client/entity.rb', line 175

def define_readers(attr_names)
  if @_readers_defined.nil?
    attr_names.each do |attr_name|
      if method_defined?(attr_name)
        raise "Cannot define accessor: #{attr_name}"
      else
        define_method(attr_name) do
          attributes[attr_name]
        end
      end
    end
    @_readers_defined = true
  end
end

.entity_name(value) ⇒ Object

Sets the name of this entity



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

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.



112
113
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
# File 'lib/sqlcached_client/entity.rb', line 112

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 attr_names[1].is_a?(Symbol)
          this.send(attr_names[1])
        else
          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.call(self, foreign_entity, join_attributes, true)
    else
      instance_variable_get(memoize_var) ||
        instance_variable_set(memoize_var,
          association.call(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(accessor_name)
end

.has_one(accessor_name, options) ⇒ Object

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



160
161
162
163
164
165
166
167
# File 'lib/sqlcached_client/entity.rb', line 160

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

.query(*args, &block) ⇒ Object

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



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

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



169
170
171
# File 'lib/sqlcached_client/entity.rb', line 169

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.



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

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



67
68
69
# File 'lib/sqlcached_client/entity.rb', line 67

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

.where(params, dry_run = false) ⇒ Resultset

Runs the entity query with the provided parameters

Returns:



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

def where(params, dry_run = false)
  request =
    begin
      paramIterator = -> (parameter) {
        server.format_request(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_body(
          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



232
233
234
# File 'lib/sqlcached_client/entity.rb', line 232

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

#get_association_requestsObject

class << self



214
215
216
217
218
# File 'lib/sqlcached_client/entity.rb', line 214

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

#get_associationsObject



226
227
228
229
230
# File 'lib/sqlcached_client/entity.rb', line 226

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

#set_associations_data(associations_data) ⇒ Object



220
221
222
223
224
# File 'lib/sqlcached_client/entity.rb', line 220

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

#to_hObject



236
237
238
# File 'lib/sqlcached_client/entity.rb', line 236

def to_h
  attributes
end