Skip to content

Instantly share code, notes, and snippets.

@bethesque
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bethesque/60b2732494287817bc41 to your computer and use it in GitHub Desktop.
Save bethesque/60b2732494287817bc41 to your computer and use it in GitHub Desktop.
I don't know what the name of this pattern is but I've been using it a lot recently and I like it
class Action
def self.call parameter
new(parameter).call
end
def initialize parameter
@parameter = parameter
end
def call
#do something with parameter
end
private
attr_reader :parameter
end
Action.("Hello world")

I like this pattern because:

  1. You're hiding the "new" from the user, so you can swap in any implementation you like.
  2. It makes stubbing in tests much easier because you only have to stub Action.call, not Action.new and Action.call
  3. Inside the class, you get to use instance variables and methods, rather than passing the arguments around, which lets you write cleaner code that is easier to refactor. "Class methods resist refactoring". http://blog.codeclimate.com/blog/2012/11/14/why-ruby-class-methods-resist-refactoring/

In fact, look at myronmarston's comment on that page. If he doesn't know the name for it, then I feel better about not knowing the name for it.

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