jsonize 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +40 -25
- data/Rakefile +7 -1
- data/jsonize.gemspec +8 -3
- data/lib/jsonize/cache_key.rb +15 -0
- data/lib/jsonize/extension/object.rb +13 -0
- data/lib/jsonize/extension.rb +5 -0
- data/lib/jsonize/orm/active_record.rb +1 -0
- data/lib/jsonize/version.rb +1 -1
- data/lib/jsonize.rb +168 -32
- metadata +80 -7
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9b46410dfd7eba02b89ba410e780a426f26b68ba3374d85d7f293fa2d7aa9842
|
|
4
|
+
data.tar.gz: 8ba98ee8661491ea6b3657ef85f2342d54052fe3c3b814125ac0b80f2532a643
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 6ad99c2157a0e6530c254bea9b5827a2c87b138c994982e16d809ace7c88a7f35737b91e1824fa0e47778c0d7e69af32c503af0f3df199ae62195644b300eb02
|
|
7
|
+
data.tar.gz: e9246d968f74e684e8c8ac24990a7aa1438efa83e566f9ca47c93ce1aca0f0c41f9f794b038fecd1985c277c08a61b3a89e362b6e3cf1ac2c4cf12617f457cc5
|
data/README.md
CHANGED
|
@@ -1,44 +1,59 @@
|
|
|
1
1
|
# Jsonize
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
Add this line to your application's Gemfile:
|
|
3
|
+
`jsonize(options = {})` converts an ActiveRecord record, relation, array, hash,
|
|
4
|
+
or ordinary Ruby value into JSON-compatible data. Hash keys become strings;
|
|
5
|
+
ActiveSupport converts ordinary dates and times. Model dates use ISO 8601;
|
|
6
|
+
model timestamps include the timezone so browser timers can parse them
|
|
7
|
+
consistently. Finite Float attributes, including
|
|
8
|
+
computed attributes, remain JSON numbers in records and relations.
|
|
10
9
|
|
|
11
10
|
```ruby
|
|
12
|
-
gem 'jsonize'
|
|
11
|
+
gem 'jsonize', git: 'https://codeberg.org/majioa/jsonize.git', ref: '<commit>'
|
|
13
12
|
```
|
|
14
13
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
```ruby
|
|
15
|
+
article.jsonize(only: [:id, :title])
|
|
16
|
+
Article.where(published: true).jsonize(only: [:id, :title])
|
|
17
|
+
{ items: [article], visible: false }.jsonize
|
|
18
|
+
Date.new(2026, 11, 8).jsonize # => '2026-11-08'
|
|
19
|
+
```
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
## Fields and external data
|
|
20
22
|
|
|
21
|
-
|
|
23
|
+
`only` selects fields; `except` excludes them. String and Symbol field names
|
|
24
|
+
are equivalent. Records exclude `created_at` and `updated_at` by default.
|
|
25
|
+
Use an array of hashes for nested field selections:
|
|
22
26
|
|
|
23
|
-
|
|
27
|
+
```ruby
|
|
28
|
+
{ items: [{ id: 1, secret: 'hidden' }] }.jsonize(only: [{ items: [:id] }])
|
|
29
|
+
# => {'items' => [{'id' => 1}]}
|
|
24
30
|
|
|
25
|
-
|
|
31
|
+
article.jsonize(externals: { calendar: 'julian' })
|
|
32
|
+
```
|
|
26
33
|
|
|
27
|
-
|
|
34
|
+
`externals` adds fields to a record representation. Computed SQL fields with
|
|
35
|
+
an `_` prefix are available without that prefix, such as `_title` as `title`.
|
|
36
|
+
Serialization preserves the supplied options and source collections.
|
|
28
37
|
|
|
29
|
-
|
|
38
|
+
## Caching
|
|
30
39
|
|
|
31
|
-
|
|
40
|
+
Record cache keys include the current attributes, SQL projection, and complete
|
|
41
|
+
serialization options, including `externals`. Relation cache keys include SQL
|
|
42
|
+
and serialization options. Repeated calls with the same data reuse the cache.
|
|
43
|
+
Plain hashes and arrays retain their own keys, shape, and current values.
|
|
32
44
|
|
|
33
|
-
|
|
45
|
+
New records, loaded relations, SQL containing `random()`, and options that
|
|
46
|
+
cannot be serialized for a cache key are processed directly. Records within
|
|
47
|
+
a relation can still use their own contextual cache.
|
|
48
|
+
To invalidate a representation, pass the same options:
|
|
34
49
|
|
|
35
|
-
|
|
50
|
+
```ruby
|
|
51
|
+
article.dejsonize(only: [:id, :title], externals: { calendar: 'julian' })
|
|
52
|
+
```
|
|
36
53
|
|
|
54
|
+
`as_json` remains a Rails compatibility adapter within the library.
|
|
55
|
+
Use `jsonize` as the application serialization API.
|
|
37
56
|
|
|
38
57
|
## License
|
|
39
58
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
## Code of Conduct
|
|
43
|
-
|
|
44
|
-
Everyone interacting in the Jsonize project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/jsonize/blob/master/CODE_OF_CONDUCT.md).
|
|
59
|
+
[MIT](LICENSE.txt).
|
data/Rakefile
CHANGED
data/jsonize.gemspec
CHANGED
|
@@ -8,15 +8,15 @@ Gem::Specification.new do |spec|
|
|
|
8
8
|
|
|
9
9
|
spec.summary = %q{Act as as_json for active record model or as a jsonize}
|
|
10
10
|
spec.description = %q{Act as as_json for active record model or as a jsonize using the cacheable redisize}
|
|
11
|
-
spec.homepage = "https://
|
|
11
|
+
spec.homepage = "https://codeberg.org/majioa/jsonize"
|
|
12
12
|
spec.license = "MIT"
|
|
13
13
|
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
|
|
14
14
|
|
|
15
15
|
spec.metadata["allowed_push_host"] = "https://rubygems.org"
|
|
16
16
|
|
|
17
17
|
spec.metadata["homepage_uri"] = spec.homepage
|
|
18
|
-
spec.metadata["source_code_uri"] = "https://
|
|
19
|
-
spec.metadata["changelog_uri"] = "https://
|
|
18
|
+
spec.metadata["source_code_uri"] = "https://codeberg.org/majioa/jsonize"
|
|
19
|
+
spec.metadata["changelog_uri"] = "https://codeberg.org/majioa/jsonize/CHANGELOG.md"
|
|
20
20
|
|
|
21
21
|
# Specify which files should be added to the gem when it is released.
|
|
22
22
|
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
|
@@ -29,4 +29,9 @@ Gem::Specification.new do |spec|
|
|
|
29
29
|
spec.add_runtime_dependency('redisize')
|
|
30
30
|
spec.add_runtime_dependency('activerecord', '>= 4.2')
|
|
31
31
|
spec.add_development_dependency('pry')
|
|
32
|
+
spec.add_development_dependency('rails', '~> 7.0.8')
|
|
33
|
+
spec.add_development_dependency('cucumber', '~> 5.3')
|
|
34
|
+
spec.add_development_dependency('rspec-expectations', '~> 3.0')
|
|
35
|
+
spec.add_development_dependency('rspec-mocks', '~> 3.0')
|
|
36
|
+
spec.add_development_dependency('sqlite3', '~> 1.4')
|
|
32
37
|
end
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
require 'digest'
|
|
2
|
+
|
|
3
|
+
module Jsonize
|
|
4
|
+
# Разделяет версии представлений и не помещает исходные данные в имя ключа.
|
|
5
|
+
module CacheKey
|
|
6
|
+
# Строит отпечаток схемы и контекста; неподдерживаемые Marshal значения дают nil.
|
|
7
|
+
# @param value [Object] Параметры и данные, влияющие на представление.
|
|
8
|
+
# @return [String, nil] Версионный SHA256-ключ либо nil для обхода кеша.
|
|
9
|
+
def self.digest value
|
|
10
|
+
'jsonize/v3/' + Digest::SHA256.hexdigest(Marshal.dump(value))
|
|
11
|
+
rescue TypeError
|
|
12
|
+
nil
|
|
13
|
+
end
|
|
14
|
+
end
|
|
15
|
+
end
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
require 'active_support/core_ext/object/json'
|
|
2
|
+
|
|
3
|
+
module Jsonize::Extension
|
|
4
|
+
# Адаптер обычных Ruby-значений к единому API jsonize.
|
|
5
|
+
module Object
|
|
6
|
+
# Преобразует число, дату и другие значения стандартным адаптером Rails.
|
|
7
|
+
# @param options [Hash] Параметры стандартной JSON-сериализации Rails.
|
|
8
|
+
# @return [Object] JSON-совместимое значение без дополнительного кеша.
|
|
9
|
+
def jsonize options = {}
|
|
10
|
+
as_json(options)
|
|
11
|
+
end
|
|
12
|
+
end
|
|
13
|
+
end
|
data/lib/jsonize/version.rb
CHANGED
data/lib/jsonize.rb
CHANGED
|
@@ -3,6 +3,8 @@ require 'redisize'
|
|
|
3
3
|
require "jsonize/version"
|
|
4
4
|
|
|
5
5
|
module Jsonize
|
|
6
|
+
autoload :CacheKey, 'jsonize/cache_key'
|
|
7
|
+
autoload :Extension, 'jsonize/extension'
|
|
6
8
|
DEFAULT_EXCEPT_ATTRS = [:created_at, :updated_at]
|
|
7
9
|
|
|
8
10
|
JSONIZE_ATTRS = {
|
|
@@ -14,7 +16,7 @@ module Jsonize
|
|
|
14
16
|
ActiveRecord: 'active_record'
|
|
15
17
|
}
|
|
16
18
|
|
|
17
|
-
JSON_TYPES = [String, Integer, TrueClass, FalseClass, NilClass, Hash, Array]
|
|
19
|
+
JSON_TYPES = [String, Integer, Float, TrueClass, FalseClass, NilClass, Hash, Array]
|
|
18
20
|
|
|
19
21
|
def default_except_attributes
|
|
20
22
|
DEFAULT_EXCEPT_ATTRS
|
|
@@ -34,18 +36,18 @@ module Jsonize
|
|
|
34
36
|
end
|
|
35
37
|
|
|
36
38
|
def generate_relation rela, source_in, options
|
|
37
|
-
|
|
38
|
-
{} :
|
|
39
|
+
attr_props = source_in.is_a?(Hash) ? source_in : source_in.polymorphic? ?
|
|
40
|
+
{} : jsonize_scheme_for(source_in.klass, attibute_tree(source_in.klass, options))
|
|
39
41
|
|
|
40
42
|
case rela
|
|
41
43
|
when Enumerable
|
|
42
44
|
rela.map do |rec|
|
|
43
|
-
generate_json(rec,
|
|
45
|
+
generate_json(rec, attr_props, options)
|
|
44
46
|
end
|
|
45
47
|
when NilClass
|
|
46
48
|
nil
|
|
47
49
|
when Object
|
|
48
|
-
generate_json(rela,
|
|
50
|
+
generate_json(rela, attr_props, options)
|
|
49
51
|
end
|
|
50
52
|
end
|
|
51
53
|
|
|
@@ -57,11 +59,27 @@ module Jsonize
|
|
|
57
59
|
[props].flatten.reduce(nil) do |r, source|
|
|
58
60
|
case source
|
|
59
61
|
when UnboundMethod
|
|
60
|
-
r
|
|
62
|
+
r.nil? ?
|
|
63
|
+
begin
|
|
64
|
+
source.bind(flow)[]
|
|
65
|
+
rescue ActiveModel::MissingAttributeError, TypeError, NoMethodError => e
|
|
66
|
+
rescue Exception => e
|
|
67
|
+
$stderr.puts("#{e.class}[#{source}]: #{e.message}")
|
|
68
|
+
end : r
|
|
61
69
|
when Proc
|
|
62
|
-
r
|
|
70
|
+
r.nil? ? source[flow] : r
|
|
63
71
|
when Hash, ActiveRecord::Reflection::AbstractReflection
|
|
64
|
-
|
|
72
|
+
if r.nil?
|
|
73
|
+
o = !options[:only] ? options :
|
|
74
|
+
options[:only].is_a?(Hash) ? options.merge(only: options[:only][name]) :
|
|
75
|
+
options.merge(only: nil)
|
|
76
|
+
|
|
77
|
+
generate_relation(flow.respond_to?(name) ? flow.send(name) : nil, source, o)
|
|
78
|
+
else
|
|
79
|
+
r
|
|
80
|
+
end
|
|
81
|
+
when NilClass
|
|
82
|
+
r
|
|
65
83
|
else
|
|
66
84
|
raise
|
|
67
85
|
end
|
|
@@ -71,36 +89,61 @@ module Jsonize
|
|
|
71
89
|
end
|
|
72
90
|
end
|
|
73
91
|
|
|
92
|
+
# Preserves JSON primitives and formats model dates/times as ISO 8601.
|
|
93
|
+
# Values with iso8601 use that representation; other objects retain to_s.
|
|
94
|
+
# @param value_in [Object] An ActiveRecord attribute or computed model value.
|
|
95
|
+
# @return [Object, String] The primitive value or its string representation.
|
|
74
96
|
def proceed_value value_in
|
|
75
|
-
(value_in.class.ancestors & JSON_TYPES).any?
|
|
97
|
+
return value_in if (value_in.class.ancestors & JSON_TYPES).any?
|
|
98
|
+
|
|
99
|
+
value_in.respond_to?(:iso8601) ? value_in.iso8601 : value_in.to_s
|
|
76
100
|
end
|
|
77
101
|
|
|
78
102
|
def prepare_attributes model, attrs
|
|
79
103
|
attrs.reduce({}) do |h, x|
|
|
80
104
|
if x.is_a?(Hash)
|
|
81
105
|
x.reduce(h) do |hh, (sub, subattrs)|
|
|
82
|
-
|
|
83
|
-
|
|
106
|
+
case subattrs
|
|
107
|
+
when Hash, Array
|
|
108
|
+
if submodel = model.reflect_on_association(sub)&.klass
|
|
109
|
+
collect_attributes(hh, model, sub, sub.to_sym, prepare_attributes(submodel, subattrs))
|
|
110
|
+
else
|
|
111
|
+
collect_attributes(hh, model, sub, sub.to_sym, nil)
|
|
112
|
+
end
|
|
113
|
+
when Symbol, String
|
|
114
|
+
collect_attributes(hh, model, subattrs.to_s, sub.to_sym, nil)
|
|
84
115
|
else
|
|
85
116
|
hh
|
|
86
117
|
end
|
|
87
118
|
end
|
|
88
119
|
else
|
|
89
|
-
|
|
90
|
-
model._reflections[x.to_s],
|
|
91
|
-
model.instance_methods.include?(x.to_sym) ? model.instance_method(x.to_sym) : nil,
|
|
92
|
-
(self.class == model ? self.attribute_names : model.attribute_names).
|
|
93
|
-
include?(x.to_s) ? ->(this) { this.read_attribute(x) } : nil
|
|
94
|
-
].compact
|
|
95
|
-
|
|
96
|
-
h.merge(x.to_s.sub(/^_/, '').to_sym => props)
|
|
120
|
+
collect_attributes(h, model, x, x.to_s.sub(/^_/, '').to_sym, nil)
|
|
97
121
|
end
|
|
98
122
|
end
|
|
99
123
|
end
|
|
100
124
|
|
|
125
|
+
def collect_attributes h, model, name, key, value
|
|
126
|
+
base = [ ->(this) { this.respond_to?(:read_attribute) ? this.read_attribute("_#{name}") : nil } ]
|
|
127
|
+
|
|
128
|
+
props =
|
|
129
|
+
unless value
|
|
130
|
+
[model.reflect_on_association(name),
|
|
131
|
+
model.instance_methods.include?(name.to_sym) ? model.instance_method(name.to_sym) : nil,
|
|
132
|
+
->(this) { this.is_a?(Hash) ? this[name] : nil },
|
|
133
|
+
(self.class == model ? self.attribute_names : model.attribute_names).include?(name.to_s) ?
|
|
134
|
+
->(this) { this.respond_to?(:read_attribute) ? this.read_attribute(name) :
|
|
135
|
+
this.respond_to?(name) ? this.send(name) : nil } : nil,
|
|
136
|
+
].compact
|
|
137
|
+
else
|
|
138
|
+
[value]
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
h.merge(key => base.concat(props))
|
|
142
|
+
end
|
|
143
|
+
|
|
101
144
|
def attibute_tree klass, options = {}
|
|
102
145
|
options[:only] ||
|
|
103
|
-
|
|
146
|
+
jsonize_attributes_except(self.class == klass ? self.attribute_names : klass.attribute_names,
|
|
104
147
|
options[:except] || default_except_attributes)
|
|
105
148
|
end
|
|
106
149
|
|
|
@@ -108,14 +151,12 @@ module Jsonize
|
|
|
108
151
|
jsonize_schemes[attr_tree] ||= prepare_attributes(klass, attr_tree)
|
|
109
152
|
end
|
|
110
153
|
|
|
154
|
+
# Исключает поля, не изменяя список атрибутов модели или входной массив.
|
|
155
|
+
# @param a_in [Array<String>] Имена доступных атрибутов.
|
|
156
|
+
# @param except_in [Array<String, Symbol>] Исключаемые имена полей.
|
|
157
|
+
# @return [Array<String>] Новый список доступных полей.
|
|
111
158
|
def jsonize_attributes_except a_in, except_in
|
|
112
|
-
except_in.
|
|
113
|
-
if res.include?(name)
|
|
114
|
-
res.delete(name)
|
|
115
|
-
end
|
|
116
|
-
|
|
117
|
-
res
|
|
118
|
-
end
|
|
159
|
+
a_in - except_in.map(&:to_s)
|
|
119
160
|
end
|
|
120
161
|
|
|
121
162
|
def jsonize_schemes
|
|
@@ -129,18 +170,31 @@ module Jsonize
|
|
|
129
170
|
@primary_key
|
|
130
171
|
end
|
|
131
172
|
|
|
173
|
+
# Сериализует запись с учётом схемы, параметров и текущей SQL-проекции.
|
|
174
|
+
# Для новой записи или некешируемых параметров строит результат напрямую.
|
|
175
|
+
# @param options [Hash] only/except, externals и контекст представления.
|
|
176
|
+
# @return [Hash] Представление записи со строковыми ключами.
|
|
132
177
|
def jsonize options = {}
|
|
133
178
|
attr_tree = attibute_tree(self.class, options)
|
|
179
|
+
scheme = CacheKey.digest([attr_tree, options, attributes])
|
|
180
|
+
attr_props = jsonize_scheme_for(self.class, attr_tree)
|
|
181
|
+
|
|
182
|
+
return generate_json(self, attr_props, options) if new_record? || scheme.nil?
|
|
134
183
|
|
|
135
|
-
redisize_json(
|
|
136
|
-
attr_props = jsonize_scheme_for(self.class, attr_tree)
|
|
184
|
+
redisize_json(scheme) do
|
|
137
185
|
generate_json(self, attr_props, options)
|
|
138
186
|
end
|
|
139
187
|
end
|
|
140
188
|
|
|
189
|
+
# Сбрасывает представление с той же схемой, параметрами и проекцией.
|
|
190
|
+
# Для некешируемых параметров возвращает nil без обращения к кешу.
|
|
191
|
+
# @param options [Hash] Параметры соответствующего вызова jsonize.
|
|
192
|
+
# @return [Object, nil] Результат постановки сброса в очередь либо nil.
|
|
141
193
|
def dejsonize options = {}
|
|
142
194
|
attr_tree = attibute_tree(self.class, options)
|
|
143
|
-
|
|
195
|
+
scheme = CacheKey.digest([attr_tree, options, attributes])
|
|
196
|
+
|
|
197
|
+
deredisize_json(scheme) unless scheme.nil?
|
|
144
198
|
end
|
|
145
199
|
|
|
146
200
|
def as_json options = {}
|
|
@@ -149,10 +203,91 @@ module Jsonize
|
|
|
149
203
|
generate_json(self, attr_props, options)
|
|
150
204
|
end
|
|
151
205
|
|
|
206
|
+
module Collection
|
|
207
|
+
# Преобразует значения коллекции; кеширование записей выполняется их jsonize.
|
|
208
|
+
# @param context [Hash] Схема полей и параметры вложенных значений.
|
|
209
|
+
# @return [Hash, Array, Object] JSON-совместимое представление коллекции.
|
|
210
|
+
def jsonize context = {}
|
|
211
|
+
as_pure_json(context)
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
# Передаёт вложенному ключу его only/except, сохраняя остальные параметры.
|
|
215
|
+
# @param context [Hash] Родительский контекст представления.
|
|
216
|
+
# @param key [Object] Ключ Hash; String и Symbol с одним именем равнозначны.
|
|
217
|
+
# @return [Hash] Новый контекст с вложенной схемой либо nil в полях без схемы.
|
|
218
|
+
def recontext context, key
|
|
219
|
+
context.merge(only: nested_jsonize_option(context[:only], key),
|
|
220
|
+
except: nested_jsonize_option(context[:except], key))
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
# Ищет схему вложенного ключа; без подходящего Hash возвращает nil.
|
|
224
|
+
# @param filter [Array, Hash, nil] Значение only или except.
|
|
225
|
+
# @param key [Object] Имя вложенного поля.
|
|
226
|
+
# @return [Object, nil] Схема найденного поля либо nil.
|
|
227
|
+
def nested_jsonize_option filter, key
|
|
228
|
+
[filter].flatten(1).each do |entry|
|
|
229
|
+
next unless entry.is_a?(Hash)
|
|
230
|
+
|
|
231
|
+
pair = entry.find { |field, _value| field.to_s == key.to_s }
|
|
232
|
+
|
|
233
|
+
return pair.last if pair
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
nil
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# Обрабатывает Hash по ключам, Array по элементам; прочие Enumerable — адаптером Rails.
|
|
240
|
+
# @param context [Hash] only/except и вложенные схемы полей.
|
|
241
|
+
# @return [Hash, Array, Object] Новое представление без изменения исходных данных.
|
|
242
|
+
def as_pure_json context = {}
|
|
243
|
+
case self
|
|
244
|
+
when Hash
|
|
245
|
+
jsonize_fields(context).map do |key, value_in|
|
|
246
|
+
new_context = recontext(context, key)
|
|
247
|
+
value = value_in.jsonize(new_context)
|
|
248
|
+
|
|
249
|
+
[key.to_s, value]
|
|
250
|
+
end.to_h
|
|
251
|
+
when Array
|
|
252
|
+
map { |value_in| value_in.jsonize(context) }
|
|
253
|
+
else
|
|
254
|
+
as_json(context)
|
|
255
|
+
end
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
# Выбирает поля Hash по only либо except; без фильтра возвращает исходный Hash.
|
|
259
|
+
# @param context [Hash] only имеет приоритет перед except; имена String/Symbol равнозначны.
|
|
260
|
+
# @return [Hash] Выбранные поля без изменения исходного Hash или схемы.
|
|
261
|
+
def jsonize_fields context
|
|
262
|
+
filter = context[:only] || context[:except]
|
|
263
|
+
|
|
264
|
+
return self unless filter
|
|
265
|
+
|
|
266
|
+
fields = [filter].flatten(1).flat_map { |entry| entry.is_a?(Hash) ? entry.keys : entry }.map(&:to_s)
|
|
267
|
+
|
|
268
|
+
select do |key, _value|
|
|
269
|
+
present = fields.include?(key.to_s)
|
|
270
|
+
|
|
271
|
+
context[:only] ? present : !present
|
|
272
|
+
end
|
|
273
|
+
end
|
|
274
|
+
end
|
|
275
|
+
|
|
152
276
|
module Relation
|
|
277
|
+
# Сериализует выборку с кешем по SQL и полному контексту представления.
|
|
278
|
+
# Загруженная выборка, random() или некешируемый контекст обрабатываются напрямую.
|
|
279
|
+
# @param context [Hash] only/except, externals и прочие параметры представления.
|
|
280
|
+
# @return [Array<Hash>] Представления записей в порядке выборки.
|
|
153
281
|
def jsonize context = {}
|
|
154
|
-
|
|
155
|
-
|
|
282
|
+
sql = to_sql
|
|
283
|
+
scheme = CacheKey.digest(context)
|
|
284
|
+
|
|
285
|
+
return to_a.jsonize(context) if loaded? || sql.match(/\brandom\s*\(/i) || scheme.nil?
|
|
286
|
+
|
|
287
|
+
key = ['sql', name, primary_key, scheme, sql]
|
|
288
|
+
|
|
289
|
+
redisize_by_key(key) do
|
|
290
|
+
to_a.jsonize(context)
|
|
156
291
|
end
|
|
157
292
|
end
|
|
158
293
|
|
|
@@ -182,5 +317,6 @@ module Jsonize
|
|
|
182
317
|
end
|
|
183
318
|
end
|
|
184
319
|
|
|
320
|
+
::Object.include(Jsonize::Extension::Object)
|
|
185
321
|
self.detect_orm
|
|
186
322
|
end
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: jsonize
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.4.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Pavel «Malo» Skrylev
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: exe
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date:
|
|
11
|
+
date: 2026-11-27 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: redisize
|
|
@@ -52,6 +52,76 @@ dependencies:
|
|
|
52
52
|
- - ">="
|
|
53
53
|
- !ruby/object:Gem::Version
|
|
54
54
|
version: '0'
|
|
55
|
+
- !ruby/object:Gem::Dependency
|
|
56
|
+
name: rails
|
|
57
|
+
requirement: !ruby/object:Gem::Requirement
|
|
58
|
+
requirements:
|
|
59
|
+
- - "~>"
|
|
60
|
+
- !ruby/object:Gem::Version
|
|
61
|
+
version: 7.0.8
|
|
62
|
+
type: :development
|
|
63
|
+
prerelease: false
|
|
64
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
65
|
+
requirements:
|
|
66
|
+
- - "~>"
|
|
67
|
+
- !ruby/object:Gem::Version
|
|
68
|
+
version: 7.0.8
|
|
69
|
+
- !ruby/object:Gem::Dependency
|
|
70
|
+
name: cucumber
|
|
71
|
+
requirement: !ruby/object:Gem::Requirement
|
|
72
|
+
requirements:
|
|
73
|
+
- - "~>"
|
|
74
|
+
- !ruby/object:Gem::Version
|
|
75
|
+
version: '5.3'
|
|
76
|
+
type: :development
|
|
77
|
+
prerelease: false
|
|
78
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
79
|
+
requirements:
|
|
80
|
+
- - "~>"
|
|
81
|
+
- !ruby/object:Gem::Version
|
|
82
|
+
version: '5.3'
|
|
83
|
+
- !ruby/object:Gem::Dependency
|
|
84
|
+
name: rspec-expectations
|
|
85
|
+
requirement: !ruby/object:Gem::Requirement
|
|
86
|
+
requirements:
|
|
87
|
+
- - "~>"
|
|
88
|
+
- !ruby/object:Gem::Version
|
|
89
|
+
version: '3.0'
|
|
90
|
+
type: :development
|
|
91
|
+
prerelease: false
|
|
92
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
93
|
+
requirements:
|
|
94
|
+
- - "~>"
|
|
95
|
+
- !ruby/object:Gem::Version
|
|
96
|
+
version: '3.0'
|
|
97
|
+
- !ruby/object:Gem::Dependency
|
|
98
|
+
name: rspec-mocks
|
|
99
|
+
requirement: !ruby/object:Gem::Requirement
|
|
100
|
+
requirements:
|
|
101
|
+
- - "~>"
|
|
102
|
+
- !ruby/object:Gem::Version
|
|
103
|
+
version: '3.0'
|
|
104
|
+
type: :development
|
|
105
|
+
prerelease: false
|
|
106
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
107
|
+
requirements:
|
|
108
|
+
- - "~>"
|
|
109
|
+
- !ruby/object:Gem::Version
|
|
110
|
+
version: '3.0'
|
|
111
|
+
- !ruby/object:Gem::Dependency
|
|
112
|
+
name: sqlite3
|
|
113
|
+
requirement: !ruby/object:Gem::Requirement
|
|
114
|
+
requirements:
|
|
115
|
+
- - "~>"
|
|
116
|
+
- !ruby/object:Gem::Version
|
|
117
|
+
version: '1.4'
|
|
118
|
+
type: :development
|
|
119
|
+
prerelease: false
|
|
120
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
121
|
+
requirements:
|
|
122
|
+
- - "~>"
|
|
123
|
+
- !ruby/object:Gem::Version
|
|
124
|
+
version: '1.4'
|
|
55
125
|
description: Act as as_json for active record model or as a jsonize using the cacheable
|
|
56
126
|
redisize
|
|
57
127
|
email:
|
|
@@ -70,16 +140,19 @@ files:
|
|
|
70
140
|
- bin/setup
|
|
71
141
|
- jsonize.gemspec
|
|
72
142
|
- lib/jsonize.rb
|
|
143
|
+
- lib/jsonize/cache_key.rb
|
|
144
|
+
- lib/jsonize/extension.rb
|
|
145
|
+
- lib/jsonize/extension/object.rb
|
|
73
146
|
- lib/jsonize/orm/active_record.rb
|
|
74
147
|
- lib/jsonize/version.rb
|
|
75
|
-
homepage: https://
|
|
148
|
+
homepage: https://codeberg.org/majioa/jsonize
|
|
76
149
|
licenses:
|
|
77
150
|
- MIT
|
|
78
151
|
metadata:
|
|
79
152
|
allowed_push_host: https://rubygems.org
|
|
80
|
-
homepage_uri: https://
|
|
81
|
-
source_code_uri: https://
|
|
82
|
-
changelog_uri: https://
|
|
153
|
+
homepage_uri: https://codeberg.org/majioa/jsonize
|
|
154
|
+
source_code_uri: https://codeberg.org/majioa/jsonize
|
|
155
|
+
changelog_uri: https://codeberg.org/majioa/jsonize/CHANGELOG.md
|
|
83
156
|
post_install_message:
|
|
84
157
|
rdoc_options: []
|
|
85
158
|
require_paths:
|
|
@@ -95,7 +168,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
95
168
|
- !ruby/object:Gem::Version
|
|
96
169
|
version: '0'
|
|
97
170
|
requirements: []
|
|
98
|
-
rubygems_version: 3.
|
|
171
|
+
rubygems_version: 3.5.22
|
|
99
172
|
signing_key:
|
|
100
173
|
specification_version: 4
|
|
101
174
|
summary: Act as as_json for active record model or as a jsonize
|