Hello,
It’s my first post here, I hope it’s the right place.
Someone point me that today
[2] pry(main)> class Test < ApplicationService
[2] pry(main)* option :user, model: User
[2] pry(main)* option :internal_account, default: proc { user.internal_account }, reader: :private
[2] pry(main)* end
=> Test
[3] pry(main)> service = Test.new(user: User.last, internal_account: 'a_string')
User Load (1.4ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Test:0x000055701eda2350
@internal_account="a_string",
@user=
#<User id: 2515, email: "toto@example.com", created_at: "2022-03-28 08:46:52", updated_at: "2022-08-02 10:00:09", first_name: "Jean", last_name: "Dupont", language: "fr" >>
[4] pry(main)> service.internal_account
NoMethodError: private method `internal_account' called for #<Test:0x000055701eda2350>
from (pry):11:in `irb_binding'
What I understand is that reader: private
allows to call the option (what is the purpose of dry-initializer for sure.
But in some cases it could be interesting to use dry-initializer to initialize private attributes.
For example:
DSL could look like:
class Thingy
extend Dry::Initializer::Mixin
option :an_external_dependency
option :my_internal_dependency, reader: :private, setter: :private, default: proc { [] }
# or
option :my_internal_dependency, accessor: :private, default: proc { [] }
end
Plain ruby equivalent:
class Thingy
def initialize an_external_dependency
@an_external_dependency = an_external_dependency
@my_internal_dependency = []
end
private
attr_reader :my_internal_dependency
end
I think in some cases it can be better to use dry-initializer
rather than initializing internal attributes somewhere else in the class.