These are chat archives for dry-rb/chat

28th
Nov 2018
Jaroslav
@jarosluv
Nov 28 2018 11:04
Hi there! Could you help me with dry-auto_inject? Can we use additional arguments in initialize method If we use dry-auto_inject for this class? Or initialize is needed only for dependencies in this approach?
Jaroslav
@jarosluv
Nov 28 2018 11:15
And what intentions are to use dry-initializer over dry-struct?
Nikita Shilnikov
@flash-gordon
Nov 28 2018 11:37
@jarosluv dry-auto_inject can be used for that and supports quite a bit of cases where you mix it with existing constructors
also, it improves over time, see dry-rb/dry-auto_inject#48
Jaroslav
@jarosluv
Nov 28 2018 11:45
@flash-gordon Please, see:
class DependencyContainer
  extend Dry::Container::Mixin

  register("dependency") { Object }
end

Injector = Dry::AutoInject(DependencyContainer)
class MyClass
  include Injector["dependency"]

  def initialize(name:)
    @name = name
    @object = dependency.new
  end
end

MyClass.new(name: "Foo")
# ArgumentError: unknown keyword: dependency
# from (pry):10:in `initialize'
class MyClass2
  include Injector["dependency"]

  def initialize(name:, **params)
    @name = name
    @object = dependency.new
  end
end

MyClass2.new(name: "Foo")
# NoMethodError: undefined method `new' for nil:NilClass
# from (pry):21:in `initialize'
Nikita Shilnikov
@flash-gordon
Nov 28 2018 11:47
you don't call super in your constructors
def initialize(name:, **deps)
  super(deps)
  @name = name
  @object = dependency.new
end
Jaroslav
@jarosluv
Nov 28 2018 12:49
@flash-gordon Oh, of course, I got it now. Thank you!
And maybe you can give me some examples of use-cases of dry-initializer in compare with dry-struct?
I find out that I need use this gems for objects of different purposes. But what does it mean technically?
Nikita Shilnikov
@flash-gordon
Nov 28 2018 12:53
I don't have any examples of using dry-initializer beyond library code. You can find plenty of usages in rom but I don't need it in application code because of DI and dry-auto_inject
and dry-struct is ADT in ruby, basically
that is plain structures or combinations via sums
I don't have custom constructors for structs, it would feel wrong
Jaroslav
@jarosluv
Nov 28 2018 12:56
Thank you for explanation!