alba icon indicating copy to clipboard operation
alba copied to clipboard

Change/Override params in associations

Open lukaspili opened this issue 2 years ago • 5 comments

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!

lukaspili avatar Jul 20 '22 17:07 lukaspili

@lukaspili Hi, it's currently not possible but if there're some usecases I'd like to support it. Could you share your usecase? For example, what kind of JSON output you want with given object?

okuramasafumi avatar Jul 20 '22 17:07 okuramasafumi

Thanks for the quick reply! My concrete use case is that I want to expose different attributes depending on permissions. This is a simple example with one nesting, but I have some use cases where the scope params is passed down to several nested associations.

class UserJson
  include Alba::Resource

  attributes :email_address, if: proc { params[:scope] == "session" }
end

class ContractJson
  include Alba::Resource

  one :creator, resource: UserJson # apply session scope 
  one :counter_party, resource: UserJson # apply anon scope 
end

lukaspili avatar Jul 20 '22 17:07 lukaspili

One way to achieve this goal would be to use inheritance, for example:

class UserJson
  include Alba::Resource

  attributes :email_address
end

class AnonUserJson < UserJson
  def attributes
    super.reject {|k, v| k == :email_address}
  end
end

AnonUserJson is a customized version of UserJson that rejects some attributes.

okuramasafumi avatar Jul 20 '22 18:07 okuramasafumi

Yes - that's a good suggestion. However inheritance can quickly show its limits compared to params when scope is not a single value but a list or a composition of multiple scopeA, scopeB

lukaspili avatar Jul 20 '22 18:07 lukaspili

True. Would you implement this feature on your own? If you will I can help. If not, then don't worry, I'll implement it.

okuramasafumi avatar Jul 22 '22 14:07 okuramasafumi

Sorry - I won't have time to tackle it. Thanks in advance if you do it, but if not I understand!

lukaspili avatar Aug 23 '22 13:08 lukaspili

Hi @lukaspili , at #227 I've implemented this feature. I added some descriptions to README so please could you check it and see if it's good for you?

okuramasafumi avatar Aug 30 '22 13:08 okuramasafumi

Hi @okuramasafumi sorry for the late reply. It looks good :) Thank you!

lukaspili avatar Sep 14 '22 02:09 lukaspili