1

I'm working on an application which has a lot of service objects. Usually, the job of these services is to build one or more Active Record models. To avoid tying my services to the application, I allow the user to modify the model's name. Here's an example:

class MyServiceObject
  attr_reader :options

  def initialize(options = {})
    @options = options
    @options[:foo_klass] ||= Foo
  end

  def do_something
    options[:foo_klass].new
  end
end

I thought it worked pretty well, but I've found that this solution lacks flexibility in some occasions. For example, I have a service that needs to find a model using one of its attributes. That's how I wanted to implement it:

class MyServiceObject
  attr_reader :options

  def initialize(options = {})
    @options = options

    @options[:lookup_proc] ||= Proc.new do |attribtue|
      DefaultModel.find_by_attribute(attribtue)
    end
  end

  def do_something(attribtue)
    options[:lookup_proc].call(attribtue)
  end
end

I'm not sure it's the most appropriate solution. In some articles they use another service object, a sort of "adapter", but it seems overkill for such a simple use case.

Do you have any suggestions? Shall I continue with the current approach?

Alessandro Desantis
  • 14,098
  • 1
  • 26
  • 32

0 Answers0