flexi_view 0.1.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b61d39a96b6c62e0ffaefcefb4e495a8b29120c53c995fd16709a819ec56b9d8
4
+ data.tar.gz: 7873e476bd12b730f6b31638d6302fd0c54318cafa0b6a58df074e3aa83b035a
5
+ SHA512:
6
+ metadata.gz: e05029dbc061d83c36bc20596085269a795a3fbee69133e7f42d55557e5c20c794bd20db6c3ae3fe19f19dd27357af4c741c93fdfd0d5c2f8a50f4b29952af44
7
+ data.tar.gz: d2e4f177ba0bea3b277cffe4a1dd3bb1482e267c2c524511755a466879234c66c1a19968589c1bffb57701100431509d9ae39f7d68b3235098bf46314436d98d
data/.rubocop.yml ADDED
@@ -0,0 +1,39 @@
1
+ require:
2
+ - rubocop-rspec
3
+ - rubocop-factory_bot
4
+ - rubocop-rake
5
+
6
+ AllCops:
7
+ SuggestExtensions: false
8
+
9
+ Style/StringLiterals:
10
+ Enabled: true
11
+ EnforcedStyle: double_quotes
12
+
13
+ Style/StringLiteralsInInterpolation:
14
+ Enabled: true
15
+ EnforcedStyle: double_quotes
16
+
17
+ Layout/LineLength:
18
+ Max: 120
19
+
20
+ Metrics/MethodLength:
21
+ Enabled: false
22
+
23
+ Metrics/BlockLength:
24
+ Enabled: false
25
+
26
+ Metrics/ClassLength:
27
+ Enabled: false
28
+
29
+ Lint/ConstantDefinitionInBlock:
30
+ Enabled: false
31
+
32
+ Metrics/AbcSize:
33
+ Enabled: false
34
+
35
+ Style/Documentation:
36
+ Enabled: false
37
+
38
+ Metrics/PerceivedComplexity:
39
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-07-07
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Jiren Patel
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,471 @@
1
+ # FlexiView Serializer
2
+
3
+ FlexiView is a flexible Ruby serialization library that eliminates the need for multiple serializer classes by providing dynamic views and namespaces within a single serializer definition.
4
+
5
+ ## Installation
6
+
7
+ Install the gem and add to the application's Gemfile by executing:
8
+
9
+ ```bash
10
+ bundle add flexi_view
11
+ ```
12
+
13
+ If bundler is not being used to manage dependencies, install the gem by executing:
14
+
15
+ ```bash
16
+ gem install flexi_view
17
+ ```
18
+
19
+ ## Quick Example
20
+
21
+ ```ruby
22
+ class ProductSerializer
23
+ include FlexiView::Serializer
24
+
25
+ attributes :id, :name, :price, :retailer_price
26
+ one :offer, "OfferSerializer"
27
+
28
+ view(:index).fields(:id, :name).association(:offer)
29
+
30
+ namespace(:admin) do
31
+ view(:index).fields(:id, :name, :price, :retailer_price).association(:offer)
32
+ end
33
+ end
34
+
35
+ # Usage
36
+ ProductSerializer.new(product).serializable_hash(view: :index)
37
+ ProductSerializer.new(product).serializable_hash(namespace: :admin, view: :index)
38
+ ```
39
+
40
+ ## Key Features
41
+ - **Single Serializer, Multiple Views**: Define different output formats in one class
42
+ - **Namespace Support**: Create context-specific serialization (admin, user, mobile, web)
43
+ - **Flexible Attributes**: Simple, conditional, and custom attribute definitions
44
+ - **Association Handling**: Support for both `one` and `many` relationships
45
+ - **Custom Formatters**: Global formatters for consistent data formatting
46
+ - **Meta Information**: Add pagination and other metadata with root key support
47
+
48
+ ## Core Benefits
49
+ 1. **Reduced Code Duplication**: No need for separate serializer classes for different views
50
+ 2. **BFF Pattern Ready**: Perfect for Backend for Frontend architecture with namespace support
51
+ 3. **Clean & Maintainable**: Centralized serialization logic for better organization
52
+
53
+ ## Perfect For
54
+ - API development requiring multiple response formats
55
+ - Backend for Frontend (BFF) implementations
56
+ - Applications with different user roles requiring different data views
57
+
58
+ ## Quick Help
59
+
60
+ - [Configuration](#Configuration)
61
+ - [Basic Usage](#basic-usage)
62
+ - [Defining Attributes](#defining-attributes)
63
+ - [Custom Formatters](#custom-formatters)
64
+ - [Associations](#associations)
65
+ - [Views](#views)
66
+ - [Namespaces](#namespaces)
67
+ - [Meta Information](#meta-information)
68
+ - [Serialization](#serialization)
69
+ - [Benefits](#benefits)
70
+ - [Examples](#examples)
71
+
72
+ ## Configuration
73
+
74
+ - How to use different JSON enconder gem.
75
+
76
+ Default JSON encoder gem is "json" gem..
77
+
78
+ ```ruby
79
+ require "oj"
80
+
81
+ FlexiView.json_encoder = Oj
82
+ ```
83
+
84
+ ## Basic Usage
85
+
86
+ To create a serializer, include `FlexiView::Serializer` in your class:
87
+
88
+ ```ruby
89
+ class ProductSerializer
90
+ include FlexiView::Serializer
91
+
92
+ attributes :id, :name, :price
93
+ end
94
+ ```
95
+
96
+ ## Defining Attributes
97
+
98
+ ### Simple Attributes
99
+
100
+ Define basic attributes that will be serialized:
101
+
102
+ ```ruby
103
+ attributes :id, :name, :discount
104
+ ```
105
+
106
+ ### Conditional Attributes
107
+
108
+ Add conditions to attributes using the `if` option:
109
+
110
+ ```ruby
111
+ attributes :price, :retail_price, format: :currency, if: -> { object.available? }
112
+ ```
113
+
114
+ ### Custom Attribute Blocks
115
+
116
+ Define custom attribute logic using blocks:
117
+
118
+ ```ruby
119
+ attribute :profit_margin do |object|
120
+ "#{object.calculate_profit_margin}%"
121
+ end
122
+ ```
123
+
124
+ ### Formatted Attributes
125
+
126
+ Apply formatters to attributes:
127
+
128
+ ```ruby
129
+ attributes :price, :retail_price, format: :currency
130
+ ```
131
+
132
+ ## Custom Formatters
133
+
134
+ Define custom formatters globally:
135
+
136
+ ```ruby
137
+ FlexiView.formatter :currency do |value, _serializer|
138
+ "$ #{value.to_f}"
139
+ end
140
+ ```
141
+
142
+ ## Associations
143
+
144
+ ### Has One Association
145
+
146
+ ```ruby
147
+ one :offer, "OfferSerializer"
148
+ ```
149
+
150
+ ### Has Many Association
151
+
152
+ ```ruby
153
+ many :assets, "AssetSerializer"
154
+ ```
155
+
156
+ ### Association with Custom Logic
157
+
158
+ ```ruby
159
+ many :specifications, "SpecificationSerializer" do |product|
160
+ product.specifications.not_archived
161
+ end
162
+ ```
163
+ ## Views
164
+
165
+ Views allow you to define different sets of fields and associations for different contexts.
166
+
167
+ ### Basic View Definition
168
+
169
+ ```ruby
170
+ view(:index).fields(:id, :name, :price).association(:offer).meta(:pagination)
171
+ ```
172
+
173
+ ### Multiple Views
174
+
175
+ ```ruby
176
+ view(:index).fields(:id, :name, :price).association(:offer)
177
+ view(:show).fields(:id, :name, :price, :retail_price)
178
+ ```
179
+
180
+ ### View with Associations
181
+
182
+ ```ruby
183
+ view(:index).fields(:id, :name).association(:assets, view: :show)
184
+ ```
185
+
186
+ ## Namespaces
187
+
188
+ Namespaces allow you to group views by context (e.g., admin, user, api):
189
+
190
+ ```ruby
191
+ namespace(:admin) do
192
+ view(:index)
193
+ .fields(:id, :name, :price, :available_count, :profit_margin)
194
+ .associations(:specifications, :offer, view: :index)
195
+ end
196
+ ```
197
+
198
+ ### Multiple Namespaces
199
+
200
+ ```ruby
201
+ namespace(:admin) do
202
+ view(:index).fields(:id, :name, :price, :available_count)
203
+ view(:show).fields(:id, :name, :price, :retail_price, :profit_margin)
204
+ end
205
+
206
+ namespace(:user) do
207
+ view(:index).fields(:id, :name, :price)
208
+ view(:show).fields(:id, :name, :price, :retail_price)
209
+ end
210
+ ```
211
+
212
+ ## Meta Information
213
+
214
+ Add meta information to your serialized output:
215
+
216
+ ```ruby
217
+ meta(:pagination, root_key: "products") do |objects|
218
+ { count: objects.length, page: options[:page] }
219
+ end
220
+ ```
221
+
222
+
223
+ The `root_key` parameter specifies which key in the serialized output should contain the meta information.
224
+
225
+ ## Serialization
226
+
227
+ ### Single Object Serialization
228
+
229
+ ```ruby
230
+ # Default serialization (all attributes)
231
+ ProductSerializer.new(Product.objects(1)).serializable_hash
232
+
233
+ # Using a specific view
234
+ ProductSerializer.new(Product.objects(1)).serializable_hash(view: :index)
235
+
236
+ # Using namespace and view
237
+ ProductSerializer.new(Product.objects(1)).serializable_hash(namespace: :admin, view: :index)
238
+ ```
239
+
240
+ ### Array Serialization
241
+
242
+ FlexiView can serialize both single objects and arrays of objects:
243
+
244
+ ```ruby
245
+ # Serialize array of products
246
+ ProductSerializer.new(Product.all).serializable_hash(view: :index)
247
+ ```
248
+
249
+ ## Benefits
250
+
251
+ ### 1. Single Serializer, Multiple Views
252
+ No need to create separate serializer classes for different views. Define all variations in one place:
253
+
254
+ ```ruby
255
+ class ProductSerializer
256
+ include FlexiView::Serializer
257
+
258
+ attributes :id, :name, :price, :description, :stock
259
+
260
+ view(:list).fields(:id, :name, :price)
261
+ view(:detail).fields(:id, :name, :price, :description, :stock)
262
+ view(:minimal).fields(:id, :name)
263
+ end
264
+ ```
265
+
266
+ ### 2. Easy BFF (Backend for Frontend) Pattern Implementation
267
+ Different namespaces for different frontends:
268
+
269
+ ```ruby
270
+ namespace(:mobile) do
271
+ view(:list).fields(:id, :name, :price)
272
+ end
273
+
274
+ namespace(:web) do
275
+ view(:list).fields(:id, :name, :price, :description)
276
+ end
277
+
278
+ namespace(:admin) do
279
+ view(:list).fields(:id, :name, :price, :stock, :created_at)
280
+ end
281
+ ```
282
+
283
+ ### 3. Clean and Maintainable Code
284
+ All serialization logic is centralized, making it easier to maintain and understand the different output formats.
285
+
286
+ ## Examples
287
+
288
+ ### Complete Example
289
+
290
+ ```ruby
291
+ # Define formatters
292
+ FlexiView.formatter :currency do |value, _serializer|
293
+ "$ #{value.to_f}"
294
+ end
295
+
296
+ class ProductSerializer
297
+ include FlexiView::Serializer
298
+
299
+ attributes :id, :name, :available_count
300
+ attributes :price, :retail_price, format: :currency, if: -> { object.id == 1 }
301
+
302
+ attribute :profit_margin do |object|
303
+ "#{object.calculate_profile_margin}%"
304
+ end
305
+
306
+ many :specifications, "SpecificationSerializer" do |product|
307
+ product.specifications.not_archived
308
+ end
309
+
310
+ one :offer, "OfferSerializer"
311
+
312
+ meta(:pagination, root_key: "products") do |objects|
313
+ { count: objects.length, page: options[:page] }
314
+ end
315
+
316
+ # Public views
317
+ view(:index).fields(:id, :name, :price).association(:offer).meta(:pagination)
318
+ view(:show).fields(:id, :name, :price, :retail_price)
319
+
320
+ # Admin namespace
321
+ namespace(:admin) do
322
+ view(:index)
323
+ .fields(:id, :name, :price, :available_count, :profit_margin)
324
+ .associations(:specifications, :offer, view: :index)
325
+ end
326
+ end
327
+
328
+ class AssetSerializer
329
+ include FlexiView::Serializer
330
+
331
+ attributes :id, :name, :image, :type
332
+
333
+ view(:show).fields(:id, :name, :image)
334
+ end
335
+
336
+ class OfferSerializer
337
+ include FlexiView::Serializer
338
+
339
+ attributes :id, :name, :discount
340
+ many :assets, "AssetSerializer"
341
+
342
+ view(:index).fields(:id, :name).association(:assets, view: :show)
343
+ end
344
+
345
+ # Usage examples
346
+ product = Product.find(1)
347
+
348
+ # Default serialization
349
+ ProductSerializer.new(product).serializable_hash # HASH
350
+ ProductSerializer.new(product).serializable # JSON
351
+
352
+ # Index view
353
+ ProductSerializer.new(product).serializable_hash(view: :index)
354
+ ProductSerializer.new(product).serializable(view: :index)
355
+
356
+ # Admin namespace with index view
357
+ ProductSerializer.new(product).serializable_hash(namespace: :admin, view: :index)
358
+ ProductSerializer.new(product).serializable(namespace: :admin, view: :index)
359
+ ```
360
+
361
+ ## Serializer Usage Examples
362
+
363
+ ### 1. All Attributes and Associations Serialization
364
+
365
+ ```ruby
366
+ ProductSerializer.new(Product.objects(1)).serializable_hash
367
+ ```
368
+
369
+ **Output:**
370
+ ```ruby
371
+ {:id=>1,
372
+ :name=>"Name - 1",
373
+ :available_count=>499,
374
+ :price=>"$ 53.0",
375
+ :retail_price=>"$ 86.0",
376
+ :profit_margin=>"40%",
377
+ :specifications=>[{:id=>1, :name=>"SpecName - 1", :image=>"http://test.com/test.png"}, {:id=>2, :name=>"SpecName - 2", :image=>"http://test.com/test.png"}],
378
+ :offer=>
379
+ {:id=>1,
380
+ :name=>"Offer - 1",
381
+ :discount=>18,
382
+ :assets=>
383
+ [{:id=>1, :name=>"Offer - 1", :image=>"http://test.com/test.png", :type=>"image"},
384
+ {:id=>2, :name=>"Offer - 2", :image=>"http://test.com/test.png", :type=>"image"}]}}
385
+ ```
386
+
387
+ ### 2. View Attributes and Associations Serialization
388
+
389
+ ```ruby
390
+ ProductSerializer.new(Product.objects).serializable_hash(view: :index)
391
+ ```
392
+
393
+ **Output:**
394
+ ```ruby
395
+ {:pagination=>{:count=>2, :page=>nil},
396
+ "products"=>
397
+ [{:id=>1,
398
+ :name=>"Name - 1",
399
+ :price=>"$ 87.0",
400
+ :offer=>
401
+ {:id=>1,
402
+ :name=>"Offer - 1",
403
+ :discount=>45,
404
+ :assets=>
405
+ [{:id=>1, :name=>"Offer - 1", :image=>"http://test.com/test.png", :type=>"image"},
406
+ {:id=>2, :name=>"Offer - 2", :image=>"http://test.com/test.png", :type=>"image"}]}},
407
+ {:id=>2,
408
+ :name=>"Name - 2",
409
+ :offer=>
410
+ {:id=>1,
411
+ :name=>"Offer - 1",
412
+ :discount=>25,
413
+ :assets=>
414
+ [{:id=>1, :name=>"Offer - 1", :image=>"http://test.com/test.png", :type=>"image"},
415
+ {:id=>2, :name=>"Offer - 2", :image=>"http://test.com/test.png", :type=>"image"}]}}]}
416
+ ```
417
+
418
+ ### 3. Namespace View Attributes and Associations Serialization
419
+
420
+ ```ruby
421
+ ProductSerializer.new(Product.objects).serializable_hash(namespace: :admin, view: :index)
422
+ ```
423
+
424
+ **Output:**
425
+ ```ruby
426
+ [{:id=>1,
427
+ :name=>"Name - 1",
428
+ :price=>"$ 75.0",
429
+ :available_count=>680,
430
+ :profit_margin=>"1%",
431
+ :specifications=>[{:id=>1, :name=>"SpecName - 1"}, {:id=>2, :name=>"SpecName - 2"}],
432
+ :offer=>
433
+ {:id=>1,
434
+ :name=>"Offer - 1",
435
+ :assets=>[{:id=>1, :name=>"Offer - 1", :image=>"http://test.com/test.png"}, {:id=>2, :name=>"Offer - 2", :image=>"http://test.com/test.png"}]}},
436
+ {:id=>2,
437
+ :name=>"Name - 2",
438
+ :available_count=>274,
439
+ :profit_margin=>"45%",
440
+ :specifications=>[{:id=>1, :name=>"SpecName - 1"}, {:id=>2, :name=>"SpecName - 2"}],
441
+ :offer=>
442
+ {:id=>1,
443
+ :name=>"Offer - 1",
444
+ :assets=>[{:id=>1, :name=>"Offer - 1", :image=>"http://test.com/test.png"}, {:id=>2, :name=>"Offer - 2", :image=>"http://test.com/test.png"}]}}]
445
+ ```
446
+
447
+ ### Key Differences in Output:
448
+
449
+ 1. **Default Serialization**: Returns all defined attributes and associations for a single object
450
+ 2. **View Serialization**: Returns only the fields specified in the view definition, includes meta information with root key structure
451
+ 3. **Namespace View Serialization**: Returns fields specific to the namespace view, focuses on admin-specific data like `available_count` and `profit_margin`
452
+
453
+ Notice how the view serialization includes pagination meta information at the root level with the actual data nested under the "products" key, while the namespace view returns a clean array structure focused on admin requirements.
454
+
455
+ ## Development
456
+
457
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
458
+
459
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
460
+
461
+ ## Contributing
462
+
463
+ Bug reports and pull requests are welcome on GitHub at https://github.com/jiren/flexi_view. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/jiren/flexi_view/blob/master/CODE_OF_CONDUCT.md).
464
+
465
+ ## License
466
+
467
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
468
+
469
+ ## Code of Conduct
470
+
471
+ Everyone interacting in the FlexiView project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/jiren/flexi_view/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexiView
4
+ class Association
5
+ attr_accessor :name, :serialized_name, :options, :data_block
6
+
7
+ def initialize(type, name, options, &data_block)
8
+ @type = type
9
+ @name = name
10
+ @options = options
11
+ @serialized_name = (@options[:as] || name).to_sym
12
+ @formatter = FlexiView.formatters[@options[:format]]
13
+ @data_block = data_block if block_given?
14
+ end
15
+
16
+ def serializer_class
17
+ @serializer_class ||= Object.const_get(options[:serializer_class].to_s)
18
+ end
19
+
20
+ def condition?(serializer)
21
+ return true if options[:if].nil?
22
+
23
+ if options[:if].is_a?(Proc)
24
+ serializer.instance_exec(&options[:if])
25
+ else
26
+ serializer.public_send(options[:if])
27
+ end
28
+ end
29
+
30
+ def to_data(parent_serializer, namespace, view)
31
+ parent_obj = parent_serializer.object
32
+
33
+ objects = if data_block
34
+ parent_serializer.instance_exec(parent_obj, &data_block)
35
+ else
36
+ parent_obj.public_send(name)
37
+ end
38
+
39
+ serializer = serializer_class.new(objects, options: parent_serializer.options)
40
+ serializer.serializable_hash(namespace: namespace, view: view)
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexiView
4
+ class Attribute
5
+ attr_accessor :name, :serialized_name, :options, :formatter, :data_block
6
+
7
+ def initialize(name, options, &data_block)
8
+ @name = name
9
+ @options = options || {}
10
+ @serialized_name = (@options[:as] || name).to_sym
11
+ @formatter = FlexiView.formatters[@options[:format]]
12
+ @data_block = data_block if block_given?
13
+ end
14
+
15
+ def condition?(serializer)
16
+ return true if options[:if].nil?
17
+
18
+ if options[:if].is_a?(Proc)
19
+ serializer.instance_exec(&options[:if])
20
+ else
21
+ serializer.public_send(options[:if])
22
+ end
23
+ end
24
+
25
+ def to_data(serializer)
26
+ value = if data_block
27
+ serializer.instance_exec(serializer.object, &data_block)
28
+ else
29
+ serializer.object.public_send(name)
30
+ end
31
+
32
+ formatter ? formatter.format(value) : value
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexiView
4
+ class Formatter
5
+ attr_accessor :name
6
+
7
+ def initialize(name, &block)
8
+ @name = name.to_sym
9
+ @formater_block = block
10
+ end
11
+
12
+ def format(value)
13
+ @formater_block.call(value)
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexiView
4
+ class Meta
5
+ attr_accessor :name, :root_key, :data_block
6
+
7
+ def initialize(name, root_key, &data_block)
8
+ @name = name
9
+ @root_key = root_key
10
+ @data_block = data_block if block_given?
11
+ end
12
+
13
+ def to_data(serializer)
14
+ serializer.instance_exec(serializer.objects, &data_block)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexiView
4
+ class Namespace
5
+ attr_accessor :name, :serializer, :views
6
+
7
+ def initialize(name, serializer)
8
+ @name = name
9
+ @serializer = serializer
10
+ @views = {}
11
+ end
12
+
13
+ def view(name)
14
+ @views[name.to_sym] = View.new(name.to_sym, serializer)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "attribute"
4
+ require_relative "association"
5
+ require_relative "meta"
6
+ require_relative "namespace"
7
+ require_relative "view"
8
+
9
+ module FlexiView
10
+ module Serializer
11
+ def self.included(klass)
12
+ klass.send :extend, Serializer::ClassMethods
13
+ klass.__init__
14
+ end
15
+
16
+ module ClassMethods
17
+ attr_reader :attribute_map, :association_map, :meta_map, :namespaces, :views
18
+
19
+ def __init__
20
+ @attribute_map = {}
21
+ @association_map = {}
22
+ @meta_map = {}
23
+ default_namespace = Namespace.new(:__default, self).tap { |ns| ns.view(:__default) }
24
+ @namespaces = { __default: default_namespace }
25
+ end
26
+
27
+ def __schema__
28
+ { attributes: @attribute_map.values }
29
+ end
30
+
31
+ def default_namespace
32
+ @namespaces[:__default]
33
+ end
34
+
35
+ def default_view
36
+ @namespaces[:__default].views[:__default]
37
+ end
38
+
39
+ def attribute(name, options = nil, &block)
40
+ if options && options[:format] && FlexiView.formatters[options[:format]].nil?
41
+ raise Error, "#{options[:format]} formatter not defined"
42
+ end
43
+
44
+ attr = Attribute.new(name.to_sym, options, &block)
45
+ attribute_map[attr.name] = attr
46
+ default_view.fields(attr.name)
47
+ end
48
+
49
+ # format and if params
50
+ def attributes(*names, **options)
51
+ names.each { |name| attribute(name, options) }
52
+ end
53
+
54
+ def many(name, serializer_class, options = nil, &block)
55
+ association(:many, name, serializer_class, options, &block)
56
+ end
57
+
58
+ def one(name, serializer_class, options = nil, &block)
59
+ association(:one, name, serializer_class, options, &block)
60
+ end
61
+
62
+ def meta(name, root_key:, &block)
63
+ raise Error, "code block required for meta #{name}" unless block_given?
64
+
65
+ m = Meta.new(name.to_sym, root_key.to_s, &block)
66
+ meta_map[m.name] = m
67
+ end
68
+
69
+ def view(name)
70
+ namespaces[:__default].view(name)
71
+ end
72
+
73
+ def namespace(name, &block)
74
+ raise Error, "'#{name}' namespace required code block" unless block_given?
75
+
76
+ name = name.to_sym
77
+
78
+ raise Error, "#{name} is already defined" if @namespaces[name]
79
+
80
+ @namespaces[name] = Namespace.new(name, self).tap do |ns|
81
+ ns.instance_exec(&block)
82
+ end
83
+ end
84
+
85
+ def find_view(namespace, view)
86
+ ns = namespace ? namespaces[namespace] : default_namespace
87
+
88
+ raise Error, "#{namespace} is not defined" unless ns
89
+
90
+ v = view ? ns.views[view] : ns.views[:__default]
91
+
92
+ raise Error, "#{view} is not defined for #{namespace || "default"} namespace" unless v
93
+
94
+ v
95
+ end
96
+
97
+ private
98
+
99
+ def association(type, name, serializer_class, options = nil, &block)
100
+ options ||= {}
101
+ options[:serializer_class] = serializer_class
102
+ assoc = Association.new(
103
+ type, name.to_sym, options, &block
104
+ )
105
+ association_map[assoc.name] = assoc
106
+ default_view.association(assoc.name)
107
+ end
108
+ end
109
+
110
+ attr_reader :options, :objects
111
+ attr_accessor :context, :object
112
+
113
+ def initialize(objects, options: nil)
114
+ @objects = objects
115
+ @options = options || {}
116
+ end
117
+
118
+ def serializable_hash(namespace: nil, view: nil)
119
+ v = self.class.find_view(namespace, view)
120
+ self.context = { namespace: namespace || :default, view: view || :default }
121
+ v.serializable_hash(self)
122
+ end
123
+
124
+ def serialize(namespace: nil, view: nil)
125
+ FlexiView.json_encoder.dump(
126
+ serializable_hash(namespace: namespace, view: view)
127
+ )
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexiView
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FlexiView
4
+ class View
5
+ attr_accessor :name
6
+
7
+ def initialize(name, serializer_class)
8
+ @name = name
9
+ @serializer_class = serializer_class
10
+ @fields = {}
11
+ @associations = {}
12
+ @meta = nil
13
+ end
14
+
15
+ def fields(*names)
16
+ names.each do |n|
17
+ attr = @serializer_class.attribute_map[n.to_sym]
18
+
19
+ raise FlexiView::Error, "#{n} attribute not defined for #{@serializer_class}" unless attr
20
+
21
+ @fields[attr.name] = attr
22
+ end
23
+
24
+ self
25
+ end
26
+
27
+ def associations(*names, namespace: nil, view: nil)
28
+ names.each do |name|
29
+ association(name, namespace: namespace, view: view)
30
+ end
31
+
32
+ self
33
+ end
34
+
35
+ def association(name, namespace: nil, view: nil)
36
+ assoc = @serializer_class.association_map[name.to_sym]
37
+
38
+ raise FlexiView::Error, "#{name} association not defined for #{@serializer_class}" unless assoc
39
+
40
+ @associations[name.to_sym] = { association: assoc, namespace: namespace, view: view }
41
+
42
+ self
43
+ end
44
+
45
+ def meta(name)
46
+ @meta = @serializer_class.meta_map[name.to_sym]
47
+
48
+ raise FlexiView::Error, "#{name} meta defination found for #{@serializer_class}" unless @meta
49
+
50
+ self
51
+ end
52
+
53
+ def serializable_hash(serializer)
54
+ data = if serializer.objects.is_a?(Enumerable)
55
+ serializer.objects.map { |object| serialize_object(serializer, object) }
56
+ else
57
+ serialize_object(serializer, serializer.objects)
58
+ end
59
+
60
+ return data unless @meta
61
+
62
+ {
63
+ @meta.name => @meta.to_data(serializer),
64
+ @meta.root_key => data
65
+ }
66
+ end
67
+
68
+ def serialize_object(serializer, object)
69
+ serializer.object = object
70
+ result = {}
71
+
72
+ @fields.each_value do |attr|
73
+ result[attr.serialized_name] = attr.to_data(serializer) if attr.condition?(serializer)
74
+ end
75
+
76
+ @associations.each_value do |params|
77
+ assoc = params[:association]
78
+
79
+ next unless assoc.condition?(serializer)
80
+
81
+ result[assoc.serialized_name] = assoc.to_data(
82
+ serializer,
83
+ params[:namespace],
84
+ params[:view]
85
+ )
86
+ end
87
+
88
+ result
89
+ end
90
+ end
91
+ end
data/lib/flexi_view.rb ADDED
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "flexi_view/version"
5
+ require_relative "flexi_view/formatter"
6
+ require_relative "flexi_view/serializer"
7
+
8
+ module FlexiView
9
+ class Error < StandardError; end
10
+
11
+ module ClassMethods
12
+ def json_encoder=(value)
13
+ @json_encoder = value
14
+ end
15
+
16
+ def json_encoder
17
+ @json_encoder
18
+ end
19
+
20
+ def formatter(name, &block)
21
+ raise Error, "required code block" unless block_given?
22
+
23
+ @formatters[name.to_sym] = Formatter.new(name, &block)
24
+ end
25
+
26
+ def formatters
27
+ @formatters
28
+ end
29
+
30
+ def __init__
31
+ self.json_encoder = JSON
32
+ @default_root_key = nil
33
+ @formatters = {}
34
+ end
35
+
36
+ def self.extended(base)
37
+ base.__init__
38
+ end
39
+ end
40
+
41
+ extend ClassMethods
42
+ end
@@ -0,0 +1,4 @@
1
+ module FlexiView
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,60 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: flexi_view
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jiren Patel
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Flexible object serializer. Serialize object define using namespace and
13
+ view
14
+ email:
15
+ - jirenpatel@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".rubocop.yml"
21
+ - CHANGELOG.md
22
+ - CODE_OF_CONDUCT.md
23
+ - LICENSE.txt
24
+ - README.md
25
+ - Rakefile
26
+ - lib/flexi_view.rb
27
+ - lib/flexi_view/association.rb
28
+ - lib/flexi_view/attribute.rb
29
+ - lib/flexi_view/formatter.rb
30
+ - lib/flexi_view/meta.rb
31
+ - lib/flexi_view/namespace.rb
32
+ - lib/flexi_view/serializer.rb
33
+ - lib/flexi_view/version.rb
34
+ - lib/flexi_view/view.rb
35
+ - sig/flexi_serializer.rbs
36
+ homepage: https://github.com/jiren/flexi_view
37
+ licenses:
38
+ - MIT
39
+ metadata:
40
+ homepage_uri: https://github.com/jiren/flexi_view
41
+ source_code_uri: https://github.com/jiren/flexi_view
42
+ changelog_uri: https://github.com/jiren/flexi_view
43
+ rdoc_options: []
44
+ require_paths:
45
+ - lib
46
+ required_ruby_version: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ - - ">="
49
+ - !ruby/object:Gem::Version
50
+ version: 3.1.0
51
+ required_rubygems_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: '0'
56
+ requirements: []
57
+ rubygems_version: 4.0.15
58
+ specification_version: 4
59
+ summary: Flexible object serializer. Serialize object define using namespace and view
60
+ test_files: []