Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] Is there any reason to do not overwrite the relationship methods of AMS? #65

Open
neohunter opened this issue May 5, 2021 · 1 comment

Comments

@neohunter
Copy link

neohunter commented May 5, 2021

I'm testing this gem, our application has tons of serializer, so I was thinking in overwrite all relationships with the lazy_* method.

I could write a monkey path for this, to make all has_many belongs_to has_one behave as the lazy_* ones,

So instead of do:

class PostSerializer < BaseSerializer
  lazy_has_many :comments
end

I could keep AMS syntax:

class PostSerializer < BaseSerializer
  has_many :comments # <- this would be equal to lazy_has_many
end

But is there any reason to don't do that?

# MonekyPatch 
#  https://github.com/Bajena/ams_lazy_relationships/blob/6f81ca9e45983724966ecdfc27d313e1c0943738/lib/ams_lazy_relationships/core/relationship_wrapper_methods.rb
%i[has_many belongs_to has_one].each do |relationship_type|
  alias_method :"old_#{relationship_type}", relationship_type.to_sym
  define_method(relationship_type) do |relationship_name, options = {}, &block|
    send("lazy_#{relationship_type}", relationship_name, options, &block)
  end
end

alias_method :old_define_lazy_association, :define_lazy_association
def define_lazy_association(type, name, options, block)
  old_define_lazy_association("old_#{type}", name, options, block)
end
@neohunter neohunter changed the title [Question[ Is there any reason to do not overwrite the relationship methods of AMS? [Question] Is there any reason to do not overwrite the relationship methods of AMS? May 5, 2021
@stokarenko
Copy link
Collaborator

There is at least one case when relationship methods are not the same - when referenced relation is not ActiveRecord relation in fact but appears to be a custom method like:

class PostSerializer < BaseSerializer
  has_many :comments

  def comments
    5.times.map { Comment.new }
  end
end

# .., or ..

class Post < AR::Base
  def comments
    5.times.map { Comment.new }
  end
end

# .., or even ..

class Post
  include ActiveModel::Model

  def comments
    5.times.map { Comment.new }
  end
end

This way the legacy has_many call is still working but lazy_has_many will crash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants