okuramasafumi / alba

Alba is a JSON serializer for Ruby, JRuby and TruffleRuby.
https://okuramasafumi.github.io/alba/
MIT License
934 stars 43 forks source link

Support access to `params` inside `nested` block #334

Closed heka1024 closed 1 year ago

heka1024 commented 1 year ago

Motivation

In our usecase, we want to write code like below.

class FooResource
  include Alba::Resource

  nested :foo do
    service = SomeService.new(params[:user])

    attribute :bar do |foo|
      service.bar
    end

    attribute :baz do |foo|
      service.baz
    end
  end
end

However, we can't do that because params is not available in the block.

Modification

okuramasafumi commented 1 year ago

@heka1024 Hi, thank you for the Pull Request! params is not available in class level, so making it available only within nested seems weird to me. helper introduced recently could be a solution for this problem, but I haven't tried it so maybe I'm wrong. Let me look into some possibilities for other solutions.

okuramasafumi commented 1 year ago

@heka1024 I noticed that the code below works:

class FooResource
  include Alba::Resource

  nested :foo do
    def service
      SomeService.new(params[:user])
    end

    attribute :bar do |foo|
      service.bar
    end

    attribute :baz do |foo|
      service.baz
    end
  end
end

This is not intuitive but is a solution for your problem. I'm closing this issue in favor of this solution, but feel free to reopen it if there's some problem.