Coder Social home page Coder Social logo

okuramasafumi / alba Goto Github PK

View Code? Open in Web Editor NEW
914.0 914.0 43.0 1.24 MB

Alba is a JSON serializer for Ruby, JRuby and TruffleRuby.

Home Page: https://okuramasafumi.github.io/alba/

License: MIT License

Ruby 99.83% Shell 0.08% HTML 0.09%
hacktoberfest json json-serialization json-serializer performance presenter ruby

alba's Introduction

okuramasafumi

Contact me on Codementor

Hi, my name is OKURA Masafumi, a software developer based in Tokyo, Japan, focusing on Ruby/Rails.

What I've beed working on recently

  • A new documentation tool for Ruby called Niwa. It's highly pluggable and integrates many different libraries such as RBS and RSpec. It's in very early stage.
  • I've beening developing a JSON serializer for Ruby named Alba for a few years now. It generates JSON from any Ruby object pretty fast with nice DSLs.
  • I'm also organizing a large tech conference about Ruby on Rails called Kaigi on Rails. I'm the founder and chief organizer of the event. It started in 2020 and more than 1000 joined it in 2022.
  • I'm an organizer of a few Ruby meetups. I organize Grow.rb, Entaku.rb and Rubygems Code Reading Meetup. Grow.rb is a local meetup in Tokyo focusing on Ruby techniques but due to COVID-19 it's online from this spring. Entaku.rb is an online meetup from the beginning and is fosuing on discussions. Rubygems Code Reading Meetup is a meetup where we read the source code of famous ruby gems together.
  • I translated a book, Mastering Vim into Japanese.

What I'm going to do in the future

  • I love teaching. I've been a coach in Rails Girls for more than 10 times and now I'm going to have coaching sessions for more advanced developers. If you're interested in learning Ruby and Rails, please contact me via the email on my profile.
  • I'd like to publish a book of my own. It'll be a book about Ruby on Rails and the basic of web technologies.
  • I think I need to learn a new programming language, but have not decided which one yet. Maybe Rust?

Hiring me

I have strong expertise on Ruby/Rails. I can also work on React projects with TypeScript as well.

Currently I'm looking for a job where i work for several hours per week.

In this type of work I'll give some advices about Ruby/Rails, look through the codebase to find problems and suggest solutions, and so on. If our clutures go well together, we might increase the amount of work!

Feel free to send me an email if you're interested.

Links

If you're interested to see a full list of links, visit my website.

Talk with me in ruby.social! https://ruby.social/@okuramasafumi

alba's People

Contributors

alejandroperea avatar alfonsojimenez avatar botamochi0x12 avatar danielmalaton avatar davidrunger avatar dependabot-preview[bot] avatar dependabot[bot] avatar estepnv avatar gabrielerbetta avatar geeknees avatar goalaleo avatar heka1024 avatar jaydorsey avatar jgaskins avatar mediafinger avatar naveed-ahmad avatar nilcolor avatar okuramasafumi avatar oshow avatar petergoldstein avatar serhii-sadovskyi avatar shigeyuki-fukuda avatar tashirosota avatar trevorturk avatar watson1978 avatar wuarmin avatar yasulab avatar ybiquitous avatar ydah avatar yosiat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alba's Issues

Stack level too deep

Describe the bug

Getting "Stack level too deep" if I add nested relationship.

To Reproduce

class AccountSerializer
      include Alba::Resource
      attributes :id, :role
      one :user, resource: UserSerializer
  end
class UserSerializer
      include Alba::Resource
      attributes :id, :email,:created_at
      many :accounts, resource: AccountSerializer
end

controller:
render json: AccountSerializer.new(accounts)

Expected behavior

To just render one level deep relationship and exit. Ideally we should be able how deep it can go like AMS allows.

Actual behavior

I guess it tries to re-render everything one inside another.

Environment

  • Ruby version: 2.7.6

Additional context

Rails 7

Rails integration

In a rails project, where should we create *Resource objects?

We are existing users of jsonapi-serializer in our Rails v7 project, and create *Serializer objects in app/serializers. Is that the same for Alba resources?

Also, is this path configurable? Asking this coz what if we wanna use both Alba and jsonapi-serializer in our Rails project.

Change/Override params in associations

Would it be possible to allow something like this?

class FooJson
  include Alba::Resource
  one :bar, resource: BarJson, params: { some: "other_value" }
end

FooJson.new(data, params: { some: "value" }).serialize

Thanks!

Support for `Oj::StringWriter`

Is your feature request related to a problem? Please describe.

Alba can get more performance boost with streaming encoder as panko does.

Describe the solution you'd like

Implement Oj::StringWriter support.

Additional context

I tried but it was hard enough to make it work. The programming style is quite different. If you're confident to implement the feature, please help!

Validation with type and auto-conversion

Is your feature request related to a problem? Please describe.

We sometimes want to validate input data with types. We also want to convert data with the specified type if types mismatch.

Describe the solution you'd like

class UserResource
  include Alba::Resource

  attributes :name, id: [String, true], admin: :Boolean, created_at: [String, ->(object) { object.strftime('%F')}]
end

In the code above, attributes takes arbitrary number of Symbols and Hashes. If Hash argument is included, it's interpreted as "attributes with types".
Hash argument's key is the same as normal attributes, meaning that it's the method name to call on the underlying object. The value part is either Class , Symbol representing JSON native type or Array. When the value is an Array, it's first item is treated as a type and second item is treated as a "auto converter".
"auto converter" is either one of the following.

  • true means it uses default converter. For example, when the type is String, it calls to_s on the attribute
  • false means it doesn't convert the attribute automatically (default)
  • Proc means it uses custom converter represented as a Proc

Dealing with circular associations

Consider this case.

  class AuthorResource
    include Alba::Resource
    attributes :id, :first_name, :last_name
    many :books, resource: 'BookResource'
  end

  class GenreResource
    include Alba::Resource
    attributes :id, :title, :description
    many :books, resource: 'BookResource'
  end

  class BookResource
    include Alba::Resource
    attributes :id, :title, :description, :published_at
    many :authors, resource: 'AuthorResource'
    one :genre, resource: 'GerneResource'
  end

Notice that associations is circular. Under current implementation, this causes SystemStackError due to infinite loop.

We want this to be valid usecase. For example, "a book's authors' books" is meaningful. In contrast, however, "a book's authors' books' authors' books" usually doesn't make sense.
That said, when the same resource appears more than three times, it tends to be written in different, better ways.

I'd like to introduce "same resource nest level" to Alba. The default is 2 but we can configure this value. If the same resource appears more than this config value, Alba warns and skips later resource rendering.

Alba.same_resource_nest_level # => 2

class Foo
  attr_accessor :id, :bar
end

class Bar
  attr_accessor :foo
end

class FooResource
  include Alba::Resource
  attributes :id
  one :bar, resource: 'BarResource'
end

class BarResource
  include Alba::Resource
  one :foo, resource: 'FooResource'
end

foo = Foo.new
foo.id = 1
bar = Bar.new
foo.bar = bar
bar.foo = foo

FooResource.new(foo).serialize # => '{"id":1,"bar":{"foo":{"id":1,"bar":{"foo":null}}}}'

Auto pluck for ActiveRecord

Is your feature request related to a problem? Please describe.

Using pluck for performance is a common technique in Rails, but Alba doesn't support pluck so we must fetch all columns although we might not use it.

Describe the solution you'd like

Alba.auto_pluck = true

class UserResource
  include Alba::Resource

  attributes :id
end

# User has id, name and email
class User < ApplicationRecord
end

UserResource.new(User.all).serialize
# => Now it executes `SELECT id` query instead of `SELECT *`

Add README benchmarks

Is your feature request related to a problem? Please describe.

Would it be possible to include the benchmarks as part of the README so you can showcase more of the CPU and memory performance more easily? I think these benchmarks are super helpful and would be nice to be more accessible for folks.

Describe the solution you'd like

Two ideas some to mind:

  • Add a Benchmarks section to the README and post details.
  • Add a data section to your benchmark source code, like I do with my benchmarks. This way you can keep the stats close to the source code for reference (this might be even better than throwing this in the README in case you want to keep the README shorter in length).

Describe alternatives you've considered

N/A

Additional context

Here's an sample of what I'm seeing when running the collection benchmarks in case it helps (or more for anyone reading this that might be curious):

Collection Benchmarks
Warming up --------------------------------------
                alba    14.000  i/100ms
         alba_inline    22.000  i/100ms
                 ams     1.000  i/100ms
         blueprinter    11.000  i/100ms
     fast_serializer    12.000  i/100ms
            jbuilder    18.000  i/100ms
         jserializer    20.000  i/100ms
             jsonapi    11.000  i/100ms
 jsonapi_same_format    11.000  i/100ms
               panko    58.000  i/100ms
           primalize    14.000  i/100ms
               rails    21.000  i/100ms
       representable     7.000  i/100ms
          simple_ams     5.000  i/100ms
       turbostreamer    21.000  i/100ms
Calculating -------------------------------------
                alba    150.412  (ยฑ49.9%) i/s -    588.000  in   5.186892s
         alba_inline    171.853  (ยฑ41.9%) i/s -    682.000  in   5.224603s
                 ams     19.455  (ยฑ 5.1%) i/s -     97.000  in   5.012393s
         blueprinter     86.935  (ยฑ43.7%) i/s -    330.000  in   5.023697s
     fast_serializer    110.387  (ยฑ22.6%) i/s -    516.000  in   5.092511s
            jbuilder    139.415  (ยฑ43.0%) i/s -    504.000  in   5.156183s
         jserializer    178.616  (ยฑ26.3%) i/s -    820.000  in   5.163328s
             jsonapi     85.341  (ยฑ43.4%) i/s -    297.000  in   5.033005s
 jsonapi_same_format     88.903  (ยฑ40.5%) i/s -    330.000  in   5.215683s
               panko    574.515  (ยฑ 7.7%) i/s -      2.900k in   5.088445s
           primalize    116.128  (ยฑ54.3%) i/s -    350.000  in   5.157945s
               rails    182.941  (ยฑ30.6%) i/s -    819.000  in   5.335402s
       representable     65.774  (ยฑ28.9%) i/s -    287.000  in   5.135179s
          simple_ams     45.796  (ยฑ43.7%) i/s -    145.000  in   5.423215s
       turbostreamer    179.497  (ยฑ27.9%) i/s -    798.000  in   5.157985s

Comparison:
               panko:      574.5 i/s
               rails:      182.9 i/s - 3.14x  (ยฑ 0.00) slower
       turbostreamer:      179.5 i/s - 3.20x  (ยฑ 0.00) slower
         jserializer:      178.6 i/s - 3.22x  (ยฑ 0.00) slower
         alba_inline:      171.9 i/s - 3.34x  (ยฑ 0.00) slower
                alba:      150.4 i/s - 3.82x  (ยฑ 0.00) slower
            jbuilder:      139.4 i/s - 4.12x  (ยฑ 0.00) slower
           primalize:      116.1 i/s - 4.95x  (ยฑ 0.00) slower
     fast_serializer:      110.4 i/s - 5.20x  (ยฑ 0.00) slower
 jsonapi_same_format:       88.9 i/s - 6.46x  (ยฑ 0.00) slower
         blueprinter:       86.9 i/s - 6.61x  (ยฑ 0.00) slower
             jsonapi:       85.3 i/s - 6.73x  (ยฑ 0.00) slower
       representable:       65.8 i/s - 8.73x  (ยฑ 0.00) slower
          simple_ams:       45.8 i/s - 12.55x  (ยฑ 0.00) slower
                 ams:       19.5 i/s - 29.53x  (ยฑ 0.00) slower

Calculating -------------------------------------
                alba   971.369k memsize (     0.000  retained)
                        13.019k objects (     0.000  retained)
                        12.000  strings (     0.000  retained)
         alba_inline   985.137k memsize (    11.008k retained)
                        13.077k objects (     8.000  retained)
                        12.000  strings (     0.000  retained)
                 ams     4.472M memsize (   168.000  retained)
                        60.544k objects (     1.000  retained)
                        14.000  strings (     0.000  retained)
         blueprinter     1.589M memsize (     0.000  retained)
                        22.105k objects (     0.000  retained)
                         2.000  strings (     0.000  retained)
     fast_serializer     1.232M memsize (     0.000  retained)
                        13.908k objects (     0.000  retained)
                         3.000  strings (     0.000  retained)
            jbuilder     1.774M memsize (     0.000  retained)
                        21.010k objects (     0.000  retained)
                         7.000  strings (     0.000  retained)
         jserializer   819.705k memsize (    16.800k retained)
                        10.109k objects (   100.000  retained)
                         2.000  strings (     0.000  retained)
             jsonapi     2.280M memsize (     0.000  retained)
                        32.415k objects (     0.000  retained)
                        50.000  strings (     0.000  retained)
 jsonapi_same_format     2.132M memsize (     0.000  retained)
                        30.314k objects (     0.000  retained)
                        50.000  strings (     0.000  retained)
               panko   230.418k memsize (     0.000  retained)
                         3.031k objects (     0.000  retained)
                         2.000  strings (     0.000  retained)
           primalize     1.195M memsize (     0.000  retained)
                        20.015k objects (     0.000  retained)
                         4.000  strings (     0.000  retained)
               rails     1.237M memsize (     0.000  retained)
                        13.304k objects (     0.000  retained)
                         3.000  strings (     0.000  retained)
       representable     2.869M memsize (     0.000  retained)
                        31.024k objects (     0.000  retained)
                        50.000  strings (     0.000  retained)
          simple_ams     7.901M memsize (     0.000  retained)
                        68.721k objects (     0.000  retained)
                         5.000  strings (     0.000  retained)
       turbostreamer   780.880k memsize (     0.000  retained)
                        12.144k objects (     0.000  retained)
                        33.000  strings (     0.000  retained)

Comparison:
               panko:     230418 allocated
       turbostreamer:     780880 allocated - 3.39x more
         jserializer:     819705 allocated - 3.56x more
                alba:     971369 allocated - 4.22x more
         alba_inline:     985137 allocated - 4.28x more
           primalize:    1195163 allocated - 5.19x more
     fast_serializer:    1232385 allocated - 5.35x more
               rails:    1236761 allocated - 5.37x more
         blueprinter:    1588937 allocated - 6.90x more
            jbuilder:    1774157 allocated - 7.70x more
 jsonapi_same_format:    2132489 allocated - 9.25x more
             jsonapi:    2279958 allocated - 9.89x more
       representable:    2869126 allocated - 12.45x more
                 ams:    4471529 allocated - 19.41x more
          simple_ams:    7900985 allocated - 34.29x more

[Doc] README should have some more info about filtering attributes

Discussed in #231

Originally posted by jrochkind September 15, 2022
The README section on "conditional attributes" says:

Filtering attributes with overriding convert works well for simple cases.

and

Below is an example for the same effect as filtering attributes section.

But the link on "filtering attributes section" doesn't work, I can't find a "filtering attributes" section of the README. And I can't find any references to "overriding convert" (which perhaps were in that section?)

I am interested in additional options for "filtering attributes" , what are these references? Thanks!

Let `to_json` receive an optional argument to adjust it to the implicit call of `to_json` in Rails render method

Is your feature request related to a problem? Please describe.

When I simply pass Alba resource object to render method in Rails6,

render json: FooResource.new(foo_instance)

But this raises ArgumentError coz Rails implicit call of to_json pass an argument(options) while to_json of Alba does NOT.

https://github.com/rails/rails/blob/main/actionpack/lib/action_controller/metal/renderers.rb#L156

Describe the solution you'd like

Let to_json receive an optional argument.

Feature Request: Case options

Summary

When we use Rails as an API, we want to return JSON, not HTML.
In that case, we may want to make it a camel case.
It would be nice to have an option to handle those situations.

Example

In the case of gem 'jsonapi-serializer', we can specify the cases as follows.

class UserSerializer
  include JSONAPI::Serializer

  attribute :user do |object|
    {
      last_name: object.last_name,
      first_name: object.first_name,
      phone_number: object.phone_number,
      zip: object.zip,
      prefecture: object.prefecture,
      address: object.address
    }
  end

  set_key_transform :camel_lower
end

Expected DSL

class UserSerializer
  include Alba::Resource

  attribute :user do |object|
    {
      last_name: object.last_name,
      first_name: object.first_name,
      phone_number: object.phone_number,
      zip: object.zip,
      prefecture: object.prefecture,
      address: object.address
    }
  end
  
  set_key_transform :camel_lower
end

Conditional Attribute should not call the block on failed conditions

For example,

attribute :id
attribute :name, if: proc { |object, _attr| object.respond_to?(:first_name) } do |object|
  object.first_name
end

Here, if we the conditionals fail it still executes the block and causes unexpected behavior

"#<NoMethodError: undefined method `last_name' 

the only workaround is to repeat the conditional check within the block :(

Equivalent when I don't know the model/serializer at play?

I am looking for an AMS equivalent to

          instance_serialization = ActiveModelSerializers::SerializableResource.new(local_instance).as_json

basically, I don't know what object local_instance is and what serializer class I should be using. AMS does that for me automatically.

Thank you

Can't get root_key to work (without inference)

Describe the bug

:root_key does not seem to be doing what I expect, I can't get it to have an effect. I am not using inference, but still expect to be able to specify a root key manually.

To Reproduce

class MyThing
  attr_accessor :name
  def initialize(name:)
    @name = name
  end
end

class TestSerializer
  include Alba::Resource

  root_key :widget

  attributes :name
end

TestSerializer.new( MyThing.new(name: "joe") ).serializable_hash
# => {:name=>"joe"}

Expected behavior

I expected there to be a root key in the output, like

{ widget: {:name=>"joe"} }

Actual behavior

There is no root key in the output, just {:name=>"joe"}. The root_key seems to be ignored?

This also means I can't get meta to output, because it requires a recognized root_key.

Additional context

Alba 1.6.0

I know the root_key function is integrated with "inference", I am not using alba inference, not calling Alba.enable_inference!, not sure if that matters.

default value when nil

Is your feature request related to a problem?

my previous serializer was converting nil values to an empty string.
I was wondering if Alba had a way to set this behavior ?

Describe the solution you'd like

class FooSerializer
  include Alba::Resource
  empty_strings_for_nil true # an option such as this
  attributes :foo, :bar
end

Describe alternatives you've considered

right now, I think I need to implement each attributes individually to convert, or change the output response to return nil.
But It's hard to tell how clients might behave

class FooSerializer
  include Alba::Resource

  attribute :foo do |obj|
    obj.foo || ""
  end
  attribute :bar do |obj|
    obj.bar || ""
  end
end

Additional context

image

Automatic serializer class lookup for Rails?

Is your feature request related to a problem? Please describe.

We have following code in a controller of our Rails application:

def index
  nodes = Node.where(index_conditions).map {|node| node.real_node }
  render json: nodes, action: 'index'
end

Node#real_node method is a polymorphic association like this:

class Node < ApplicationController
  belongs_to :real_node, polymorphic: true
end

Because elements of the rendered array dynamically change at runtime, I can't determine serializer class statically.

Describe the solution you'd like

To overcome the problem, I added following initializer file at config/initializers/ in our rails app:

module AlbaSerializerLookup
  CLASS_SERIALIZER_CACHE = {}

  def self.serializer_for(object, serializer: nil)
    if serializer
      if serializer.is_a?(String) || serializer.is_a?(Symbol)
        serializer = ActiveSupport::Inflector.safe_constantize(serializer)
      end
      serializer
    else
      serializer_for_class(object.class)
    end
  end

  def self.serializer_for_class(klass)
    CLASS_SERIALIZER_CACHE[klass] ||= serializer_for_class_without_cache(klass)
  end

  def self.serializer_for_class_without_cache(klass)
    # This returns ArraySerializer if klass is Array
    ActiveSupport::Inflector.safe_constantize(:"#{klass.name}Serializer")
  end
end

class ObjectSerializer
  include Alba::Resource

  def converter
    inner_params = params.dup
    inner_serializer_param = inner_params.delete(:serializer)

    lambda do |object|
      serializer = AlbaSerializerLookup.serializer_for(object, serializer: inner_serializer_param)
      if serializer && serializer != ObjectSerializer
        resource = serializer.new(object, params: inner_params)
        resource.serializable_hash
      else
        object
      end
    end
  end
end

class RootSerializer < ObjectSerializer
  def serializable_hash
    if collection? && !object.is_a?(Hash)
      root_array_serializable_hash
    else
      converter.call(object)
    end
  end

  alias to_h serializable_hash

  private

  def root_array_serializable_hash
    serializable_array = object.map(&converter)

    if object.respond_to?(:total)
      {
        data: serializable_array,
        total: object.total,
      }
    else
      {
        data: serializable_array,
      }
    end
  end
end

ActionController::Renderers.add :json do |object, options|
  resource = RootSerializer.new(object, params: options)
  string = resource.serialize
  send_data string, type: Mime[:json]
end

This approach is basically inspired by following logics of ActiveModelSerializers:

Support for render json: ... syntax is useful when we want to support both HTML and JSON response from the same controller method, although we're not using it at this moment:

def index
  nodes = Node.where(index_conditions).map {|node| node.real_node }
  respond_to do |format|
    format.json {render json: nodes}
    format.html  {render json: nodes}
  end
end

Describe alternatives you've considered

It would be great if Alba gem has out-of-the-box support for json rendering for Rails with dynamic serializer class lookup.

Additional context

Verified code snippets with:

  • rails-7.0.3
  • alba-1.6.0

Dynamic filter

Hi! Thanks for the project.

I would like to ask if there is a way to include/exclude attributes via params, for example something like this:

UserResource.new(user, exclude: {[:id]}),

should return the json without the "ID".

Thank you!

Logging

It's a good idea to provide logging facility for performance monitoring or debugging.
It might be even better to provide around hook for some methods so that users can do something (logging in this context but various things can be done) before and after the targeted methods.

possible to refactor this attribute to use a symbol ?

works fine, I'd like to write it to be easier to read it

current code

  attribute :overridden_at, if: proc { |resource|
                                  resource.respond_to?(:overridden_at) && resource.overridden_at.present?
                                } do |resource|
    resource.overridden_at.iso8601(3)
  end

Describe the solution you'd like

We need to call respond_to? because the attribute comes from a joined relation, which is not always present when calling this serializer.
then we don't want to include the field in the json when its nil, thus using the if: proc

if we could write it such as

attribute :overridden_at, if: :has_overriden_at? do |resource|
  resource.overridden_at.iso8601(3)
end

def has_overriden_at?(resource)
  resource.respond_to?(:overridden_at) && resource.overridden_at.present?
end

is this already possible?

Deep transform_keys for inline associations

Is your feature request related to a problem? Please describe.

I'd like to have an option for transform_keys to work down through inline associations. Currently, you need to repeat transform_keys within each association block.

Additional context

Here's a code example based on the README which demonstrates the issue:

class User
  attr_reader :created_at
  attr_accessor :articles

  def initialize
    @created_at = Time.now
    @articles = []
  end
end

class Article
  attr_accessor :user_id

  def initialize(user_id)
    @user_id = user_id
  end
end

class AnotherUserResource
  include Alba::Resource

  transform_keys :lower_camel

  attributes :created_at

  many :articles do
    # transform_keys :lower_camel
    
    attributes :user_id
  end
end

user = User.new
article = Article.new(1)
user.articles << article

AnotherUserResource.new(user).to_h

Note the commented-out transform_keys macro, which, when un-commented, results in the desired output. Here's an example from the console showing the difference:

# articles.user_id, not transformed into lower_camel
{:createdAt=>2022-07-26 21:18:29.721693 -0500, :articles=>[{:user_id=>1}]}
# articles.userId, transformed if you repeat the `transform_keys` within the inline association
{:createdAt=>2022-07-26 21:18:29.721693 -0500, :articles=>[{:userId=>1}]}

Ideally, I'd like to avoid repeating transform_keys for inline associations, but things do work as expected currently, so this is only a nice-to-have. I'm not sure if it would be convenient in Alba's code to make this possible, but I thought I'd mention it.

Thank you!

New backend: oj_rails

Oj has modes and many people will want to use rails mode. We should support it directly with oj_rails backend.
Current oj backend will be aliased as oj_strict.
If someone needs to use object or compat mode of oj, we'll consider supporting them too!

Question about render :json

Hi! I have another question related with render :json in rails controller.

Is there a way to automatically serialize with alba using render? If not, what is the recommended way to use alba in a rails controller.

Thank you!

Is it ok to add rake command for rails installation ?

Is your feature request related to a problem? Please describe.

Feature request.
I am using Alba with Rails then thought will be happy if we have rake command to install to rails.

Describe the solution you'd like

Add rake command to install alba setting(like initializer), alba resource file template.
Or it could be done by rails generate command.

Different style of collection serialization

Alba currently serializes a collection into an Array:

class User
  attr_reader :id

  def initialize(id)
    @id = id
  end
end

user1 = User.new(1)
user2 = User.new(2)

class UserResource
  include Alba::Resource
  attributes :id
end

UserResource.new([user1, user2]).serializable_hash
# => [{:id=>1}, {:id=>2}]

However, sometimes we want to serialize a collection into a Hash with a certain key. The interface will be like:

class UserResource
  include Alba::Resource

  collection_key :id

  attributes :id
end

With collection_key, we can specify the key for the Hash. Now UserResource will serialize a collection differently.

UserResource.new([user1, user2]).serializable_hash
# => {'1' => {:id=>1}, '2' =>  {:id=>2}}

This way, Alba provides more flexible way to deal with collections.

`root_key_for_collection` DSL

Is your feature request related to a problem? Please describe.

When setting a root key only for collection, it looks like this:

root_key :_, :foos

Here, the first :_ looks ugly but required.

Describe the solution you'd like

root_key_for_collection :foos

Describe alternatives you've considered

None.

Additional context

This is the real problem in my client work :)

Thanks for this gem

@okuramasafumi Hi again! ๐Ÿ˜„ ๐Ÿ‘‹

I just want to say thanks for your work on this gem. We was using the netflix/fast_json_api previously and we need to migrate to a new gem, and the only well-maintained gem that we found was yours. The other are abbandoned, or not stable.

๐Ÿป ๐Ÿค

Where to keep Configurations?

I am going to try this gem. As a suggestion, here it is not clear where to add the configurations. I am currently moving ahead with creation of the initialize. Maybe docs can be improved further to guide this.

alba/README.md

Line 100 in 0c6f24b

Alba.backend = :oj

Cascade key transformation only cascades for one level

Describe the bug

Apologies for not testing this myself sooner, but I think we have a bug left over from #220, where transform_keys only cascades for one level.

To Reproduce

Given the following code sample, note that the articles array has the createdAt key, but the comments array has the created_at key, which has not been transformed:

class User
  attr_accessor :created_at, :articles

  def initialize
    @created_at = Time.now
  end
end

class Article
  attr_accessor :created_at, :comments

  def initialize
    @created_at = Time.now
  end
end

class Comment
  attr_accessor :created_at

  def initialize
    @created_at = Time.now
  end
end

class UserResource
  include Alba::Resource

  transform_keys :lower_camel

  attributes :created_at

  association :articles do
    attributes :created_at

    association :comments do
      attributes :created_at
    end
  end
end

user = User.new
comment = Comment.new
article = Article.new
article.comments = [comment]
user.articles = [article]

UserResource.new(user).to_h
# => 
{"createdAt"=>2022-10-24 15:23:10.190596 -0500,
 "articles"=>[{"createdAt"=>2022-10-24 15:23:10.203395 -0500, "comments"=>[{"created_at"=>2022-10-24 15:23:10.198995 -0500}]}]}

Why not json:api?

The library looks flexible enough so adding support in my app for json:api with this gem should be trivial, was wondering if there is a deeper reason on why not supporting it, or is simply that you want to keep this gem nice and clean?

Inconsistentcy between `#serialize` (aka `#to_json`) and `#serializable_hash` (aka `#as_json`)

Hi! First of all, thank you for putting this project together! ๐Ÿ†

I'm working on a Rails project, and I stumbled across the fact that #as_json doesn't consider root keys. This stops me me from writing

render json: UserSerializer.new(user), status: :ok

in my controllers. This forces me to render a text/raw payload and take care of the content-type header. More importantly, it breaks the expectation that JSON.generate(obj.as_json) == obj.to_json.

Is this something by design? Or may I attempt to change it?

Support attribute method in resource

Is your feature request related to a problem? Please describe.

Sometimes we'd like to have a method as an attribute. For example, consider this example from README.

class User
  attr_accessor :id, :name, :email, :created_at, :updated_at
  def initialize(id, name, email)
    @id = id
    @name = name
    @email = email
    @created_at = Time.now
    @updated_at = Time.now
  end
end

class UserResource
  include Alba::Resource

  root_key :user

  attributes :id, :name

  attribute :name_with_email do |resource|
    "#{resource.name}: #{resource.email}"
  end
end

user = User.new(1, 'Masafumi OKURA', '[email protected]')
UserResource.new(user).serialize
# => "{\"user\":{\"id\":1,\"name\":\"Masafumi OKURA\",\"name_with_email\":\"Masafumi OKURA: [email protected]\"}}"

Describe the solution you'd like

class UserResource
  include Alba::Resource

  root_key :user

  attributes :id, :name, :name_with_email

  def :name_with_email(resource)
    "#{resource.name}: #{resource.email}"
  end
end

Here we define name_with_email as a method, not a block. This is useful when we want this method to be inherited.

Describe alternatives you've considered

We can leave it unimplemented since we can achieve the same goal with block syntax.

Question about Resource / Serializer, can you provide some examples ?

Hi,
I can't figure out how to implement the serializer class
I understand the ressource, but how look like the Serializer class ?

Here is what my serializer from AMS

class IssueSerializer < ActiveModel::Serializer  
  attributes :title, :subject, :description, :conversations, :due_at, :assigned_to
  belongs_to :company
end

and in controller
I would like to use with metadata pagination Pagy

 class IssuesController < ApiController
    include Pagy::Backend
    after_action { pagy_headers_merge(@pagy) if @pagy }
    rescue_from Pagy::OverflowError, with: :redirect_to_last_page

    def index
      @pagy, @isssues = Issue.scope(....)
      render json: { issues: @issues, pagination: pagy_metadata( @pagy, url: true )
   end

end

How would you advise me using Alba in this case ?
Thanks

New option: Overwriting behavior

Abstract

Code like

Class FooResource
  attributes :id, :name
  attribute :name do
    'bar'
  end
end

overwrites an attribute name with 'bar' although a user might want to define simple attribute with attributes. Maybe they misspelled it.
If Alba can warn this kind of overwriting, it'll help users to avoid unintentional overwriting.

Considered Interface

Alba.when_overwriting_attribute # => [:warn(default), :raise, :ignore]

Problems

When they overwrite attributes with inheritance:

Class FooResource
  attributes :id, :name
end

class BarResource < FooResource
  attribute :name do
    'bar'
  end
end

This should be fine.
Current implementation of attributes doesn't recognize where it's defined, so this'll be changed.

Inconsistent behaviour in collection serialization

Hi,

I was trying to serialize a collection and facing errors if attributes are used inside a block. Is this the expected behaviour?

Thanks.

To Reproduce

class User
  attr_reader :id, :created_at, :updated_at
  attr_accessor :articles

  def initialize(id)
    @id = id
    @created_at = Time.now
    @updated_at = Time.now
    @articles = []
  end
end

class Article
  attr_accessor :user_id, :title, :body

  def initialize(user_id, title, body)
    @user_id = user_id
    @title = title
    @body = body
  end
end

class ArticleResource
  include Alba::Resource

  attribute :dummy_title do |resource|
    resource.title
  end
end

class UserResource
  include Alba::Resource

  attributes :id

  many :articles, resource: ArticleResource
end

user = User.new(1)
article1 = Article.new(1, 'Hello World!', 'Hello World!!!')
user.articles << article1
article2 = Article.new(2, 'Super nice', 'Really nice!')
user.articles << article2

UserResource.new(user).serialize

Expected Behaviour

"{\"id\":1,\"articles\":[{\"dummy_title\":\"Hello World!\"},{\"dummy_title\":\"Super nice\"}]}"

Actual Behaviour

Traceback (most recent call last):
       16: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:108:in `block (2 levels) in converter'
       15: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:123:in `key_and_attribute_body_from'
       14: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:163:in `fetch_attribute'
       13: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:172:in `yield_if_within'
       12: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:163:in `block in fetch_attribute'
       11: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/many.rb:18:in `to_hash'
       10: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:66:in `serializable_hash'
        9: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:66:in `map'
        8: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:107:in `block in converter'
        7: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:107:in `map'
        6: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:107:in `each'
        5: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:108:in `block (2 levels) in converter'
        4: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:123:in `key_and_attribute_body_from'
        3: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:162:in `fetch_attribute'
        2: from /Users/ashwine/.rvm/gems/ruby-2.6.1/gems/alba-1.4.0/lib/alba/resource.rb:162:in `instance_exec'
        1: from (irb):77:in `block in <class:ArticleResource>'
NoMethodError (undefined method `title' for #<Array:0x00007f8f741e5c70>)

Environment

  • Ruby version: 2.6.1

Be able to plugin a custom inflector

Hey,

great gem!

Is your feature request related to a problem? Please describe.

If you need key transformation, but there's no active_support around, you have to create workarounds to achieve key-transformation. It would be great, if we could add the possibility to plugin a custom inflector. For example, I have a "hanami-api-dry-project" and there the dry-inflector is around. And I don't want to add the active_support-dependency.

Describe the solution you'd like

One solution might be, to be able to plugin a custom inflector, which has to provide the supported api (#camelize, #dasherize):

Alba.inflector = Dry::Inflector.new # the default one should stay ActiveSupport::Inflector

Are you interested in this feature?

Best regards and thank you

Allow conditionals on attribute

Hi,

thanks for the hard work on the Gem,
I would like to have the attribute accept conditionals to decide if that key could even be rendered.
Conditional Attributes are supported in ActiveModel::Serializer https://github.com/rails-api/active_model_serializers/tree/0-8-stable#attributes

for example, something like

attribute :id
attribute :student_name, unless: proc {|resource| resource.name.nil? }

now the resulting hash would be

  1. if resource has name
{id: 1, student_name: 'Bob'}
  1. if resource does have name
{id: 1}

Cascade key transformation seems not work for custom attribute

Describe the bug

To Reproduce

class ProjectResource
  include Alba::Resource
  transform_keys :lower_camel

  root_key :project

  attributes :id, :created_at
  attribute :project_info do |resource|
    {
      created_at: resource.created_at,
      project_name: "name"
    }
  end
end

Expected behavior

{
  "id": 191,
  "createdAt": "2022-10-17 17:42:08",
  "projectInfo": {
  "createdAt": "2022-10-17 17:42:08",
  "projectName": "name"
  }
}

Actual behavior

{
  "id": 191,
  "createdAt": "2022-10-17 17:42:08",
  "projectInfo": {
  "created_at": "2022-10-17 17:42:08",
  "project_name": "name"
  }
}

Environment

  • Ruby version: 3.1.2

Layout feature

Discussed in the discussions board, now I believe supporting layout is something we'd like to have with Alba. The user code would look like:

class UserResource
  include Alba::Resource

  layout file: 'layout.json.erb'

  # ...
end

And the layout file would be a JSON text file with erb:

{
"header": "my_header",
<%= resource.serialized_json %>
}

where resource would be Alba::Resource object.

Discussed in #142

Originally posted by toncid July 1, 2021
Hello,

Great gem you have here! ๐Ÿ‘

I was wondering if there is a way to support simple "layouts" in a way that we would have a predefined JSON template with a payload placeholder within it?

The template could look like this:

{
  status: {
    code: 200,
    message: "OK"
  },

  // payload goes here

  pagination: {
    nextPage: "..."
  }
}

The payload would then be yielded from a resource (properly inferred), like:

{
  // status

  user: {...}

  // pagination
}

Or:

{
  // status

  payments: [{...}]

  // pagination
}

Or even come with multiple subfields:

{
  // status

  user: {...},
  payments: [{...}]

  // pagination
}

I haven't found a way to accomplish this with the current gem version (v1.4.0).

Want `resource:` and `each_resources:` option to Alba.serialize like ActiveModelSerializers `serializer:` and `each_serializers:`

Is your feature request related to a problem? Please describe.

Model has many serializers in many cases.I want to select resources class.

# ex. ActiveModelSerializers
ActiveModelSerializers::SerializableResource.new(
  serializer: CustomSerializer, # This
).serializable_hash

Describe the solution you'd like

Alba.serialize(object, resource: CustomResource, root_key: :object)
Alba.serialize(objects, each_resources: CustomResource, root_key: :object)

Meta data support

Is your feature request related to a problem? Please describe.

We need some form of support for meta data alongside the main (serialized) data.

Describe the solution you'd like

class UserResource
  include Alba::Resource

  attributes :id, :name

  meta name: :size do |users|
    users.size
  end
end

UserResource.new([user1, user2], key: :users).serialize
# => '{"users":[{"id":1,"name":"user1"},{"id":2,"name":"user2"}],"size":2}'

Describe alternatives you've considered

In this proposal the return value of meta block is a Hash and it's used directly. I'm not sure if we're happy to use some sort of DSL in meta block to build a Hash.

class UserResource
  include Alba::Resource

  attributes :id, :name

  meta do |users|
    attribute :size { users.size }
  end
end

UserResource.new([user1, user2], key: :users).serialize
# => '{"users":[{"id":1,"name":"user1"},{"id":2,"name":"user2"}],"meta"{"size":2}}'

Alba and Dependency Injections

Hi,

I would like to use Alba on my app, however I am using dependency injection to play with my controllers (thanks https://dry-rb.org/gems/dry-auto_inject/0.6/ )

This gem assumes that the serializer should know about the resources it has to serialize on the initialization phase.
This breaks the possibility to use dependency injection, and so to use the serializer as an external dependency.

There is a possibility to add a way to add thing like serializer.serialize_ressource(user)

Here is an example of how I use dependency injection on a personal project (we use the same system at work) https://github.com/alex-lairan/GoldivoreBack/blob/master/src/application/controllers/raids/index.rb

It might have forget to add `with:` argument before `:active_support` in the README

I guess it is more of a typing error than a bug report about README.

Describe the bug

When I started rails process, it arose below errors after putting alba.rb file on the config/initializers directory.

/Users/subaru/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/alba-2.0.1/lib/alba.rb:57:in `enable_inference!': wrong number of arguments (given 1, expected 0; required keyword: with) (ArgumentError)
        from /Users/subaru/dev/zeroken_api/config/application.rb:29:in `<class:Application>'
        from /Users/subaru/dev/zeroken_api/config/application.rb:26:in `<module:ZerokenApi>'
        from /Users/subaru/dev/zeroken_api/config/application.rb:24:in `<top (required)>'
        from /Users/subaru/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-4.0.0/lib/spring/application.rb:93:in `require'
        from /Users/subaru/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-4.0.0/lib/spring/application.rb:93:in `preload'
        from /Users/subaru/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-4.0.0/lib/spring/application.rb:162:in `serve'
        from /Users/subaru/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-4.0.0/lib/spring/application.rb:144:in `block in run'
        from /Users/subaru/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-4.0.0/lib/spring/application.rb:138:in `loop'
        from /Users/subaru/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-4.0.0/lib/spring/application.rb:138:in `run'
        from /Users/subaru/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/spring-4.0.0/lib/spring/application/boot.rb:19:in `<top (required)>'
        from <internal:/Users/subaru/.rbenv/versions/3.0.2/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
        from <internal:/Users/subaru/.rbenv/versions/3.0.2/lib/ruby/3.0.0/rubygems/core_ext/kernel_require.rb>:85:in `require'
        from -e:1:in `<main>'

I guess the README described at here might have forget adding with: argument before :active_support.

To Reproduce

  1. create a file which is named 'alba.rb' following this guideline under config/initializers
Alba.backend = :active_support
Alba.enable_inference!(:active_support)
  1. command anything to start rails process such as rails c

Expected behavior

Rails processes will be started successfully.

% rails c
Running via Spring preloader in process 56709
Loading development environment (Rails 6.1.6.1)
irb(main):001:0> 

Actual behavior

It arises errors described above.

Environment

  • Ruby version: 3.0.2
  • Rails version: 6.1.6

Compatibility with zeitwerk

Describe the bug

When I write certain code, I get an error in zeitwerk:check.

$ rails zeitwerk:check                                                        
Hold on, I am eager loading the application.
rails aborted!
NameError: uninitialized constant CommentResource::CommentParentResource

  one :parent, resource: CommentParentResource
                         ^^^^^^^^^^^^^^^^^^^^^
/alba-zeitwerk-issue/app/resources/comment_resource.rb:7:in `<class:CommentResource>'
/alba-zeitwerk-issue/app/resources/comment_resource.rb:1:in `<main>'
/alba-zeitwerk-issue/app/resources/comment_parent_resource.rb:1:in `<main>'
Tasks: TOP => zeitwerk:check

To Reproduce

reproduction code
https://github.com/ima2251/alba-zeitwerk-issue

Expected behavior

No error in zeitwerk:check.

Actual behavior

Environment

  • Please check my repository.

Additional context

Random error when deploying to Heroku.Sometimes it deploys successfully, sometimes it fails.
The cause of the error is the same as with zeritwerk:check.

Normal code works fine, so we won't notice it during normal development, unless we do a zeitwerk:check.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.