Skip to content

Instantly share code, notes, and snippets.

@IceTimux

IceTimux/d1467.md

Last active Dec 7, 2020
Embed
What would you like to do?

~Programming ~Patterns | The Command pattern


Take a function that performs some opereation and encapsulate it into its own Class.

Take this function here for example.

def save_invoice(invoice)
  # do some processing here
end

It doesn't really matter where this function is defined. It could be inside an Invoice class if that makes you feel better.

class Invoice
  def initialize(options)
    # set whatever options and initialize an instance
  end
  
  def save
    # do some processing here
  end
end

Both examples will work, and I will show you both.

Now make a class named after the function and append Command to it! In the constructor you set the dependencies, invoice in this case.

Then make a method called execute that will perform processing for the command.

# save_invoice_command.rb
class SaveInvoiceCommand
  def initialize(invoice)
    @invoice = invoice
  end
  
  def execute
    # do some processing here
  end
end

There it is, your command!

Now you can refactor your Invoice class and save method to use the new SaveInvoiceCommand

require_relative './save_invoice_command'

class Inovice
  def initialize(options)
    # set options and initialize instance
  end
  
  def save
    command = SaveInvoiceCommand.new(self)
    command.execute
  end
end

If you were using the bare method example with the invoice being a parameterized dependency, then your refactor would look like this.

require_relative './save_invoice_command'

def save_invoice(invoice)
  command = SaveInvoiceCommand.new(invoice)
  command.execute
end


Sources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment