Skip to content

Instantly share code, notes, and snippets.

@DamirSvrtan
Last active May 24, 2018 16:58
Show Gist options
  • Save DamirSvrtan/a48c071c7ece97de31916b224fe97db5 to your computer and use it in GitHub Desktop.
Save DamirSvrtan/a48c071c7ece97de31916b224fe97db5 to your computer and use it in GitHub Desktop.

I save 10 seconds per class creation

This is how I usually write use-cases/service objects:

class UserRegistrationForm

  def self.call(access_code)
    new(access_code).call
  end

  def initialize(access_code)
    @access_code = access_code
  end
  
  def call
    ...do stuf...
  end
  
  private
  
  ..more private methods..
  
  attr_reader :access_code
end

Recently started to use this gem: attr_extras

The gem provides a couple of cool boilerplate cutdowns, the best thing being the method_object:

method_object

The method_object method does three things:

  • creates an initializer that takes in the argument you've passed it, in this case, the user, and assigns it to an instance variable @user
  • creates a private reader for that argument.
  • creates a class level call method that instantiates the object and calls the call instance method.

Replace the upper piece of code with this:

class UserRegistrationForm
  method_object :access_code
end

Benefits:

  • Shorter, remove boilerplate code
  • Easier to stub out:
    • Stubbing out a instance method: allow_any_instance_of(Widget).to receive(:name).and_return("Wibble")
    • Stubbing out a class method allow(Widget).to receive(:name).and_return("Wibble")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment