205 points · by tomblomfield · 12y ago · 167 comments
The key point for an "interactor" extraction is imo when you have multiple models being created in symphony, like a Signup model. Or if you for some reason need to reuse the behavior.
But if all your controllers look like this, with one "interactor" model per action, you're doing it wrong.
Whatever floats your boat, though. If this is what you prefer, great. But please hold the "beginner's version" crap. Plenty of large apps are built with vanilla Rails. Basecamp is one.
Perhaps if someone made a post like this with starting code that was more complex it would be a better example, and also harder for you to counter it with a couple gists ;)
To my mind, this code is much clearer, which proves the OPs point.
However, there's a distinction that has to be made in your example and the OP's. In the OP, the failure of the Interactor, including the delivery of emails, would cause the controller to enter the "failure" branch:
if interactor.success?
redirect_to home_path
else
flash[:error] = interactor.message
render :new
end
Whereas your example, the controller would take the successful branch if the data model was saved, regardless of whether email delivery failed: if @grouper.save
ConfirmedGrouperEmails.new(@grouper).deliver
AssignBarForGrouper.enqueue(@grouper.id)
redirect_to home_path
else
render :new
end
So we're not comparing apples to apples here. However, as a layperson, I'd have to agree with you: Why should the error be raised to the grouper-creating user, when it should be going to the part of the system that handles mailing? But maybe the actual details are more complicated than that...> You obviously need to choose the patterns that fit the problem you’re trying to solve – it’s rarely one-size-fits-all, and some of these principles may be overkill in a very simple 15-minute blog application. Our objection is that Rails feels like it’s a Beginners’ Version, often suggesting that one size does fit all
This quote from the post (minus the "Beginners" jibe - sorry!) is my core objection. Your example works fine if you're working with a simple application. But the "Rails Way" feels like it starts to fall over when you get to medium or large codebases.
I feel like Rails could benefit hugely from a few core "Advanced" features that help you grow a small application into a larger, functioning business. Sure, you can add them yourself, but then you lose the advantage of shared standards and strong architectural conventions. Every new developer we hire has to learn what exactly we mean by "Interactors" or "Decorators" or "Policies".
Don't even get me started on the hand-wavy "loosely coupled".
If this is a poor example, pick a good example. I'll be happy to code ping pong you whatever example you choose.
One way to spend hundreds of thousands of LOC on an application is to stuff it with needless abstractions. That doesn't make it "advanced", and it's not Rails that's falling over, it's probably just some shitty code.
Maybe that's a clue that your chosen paradigms weren't that helpful. Or rather, that they convoluted the code base instead of clarified it. It's certainly a red herring that you need to teach your abstractions to new developers and that it's an endeavor to do so.
POROs are great, though. Our app/models is full of them. We even added app/services too. The trouble I have is with people who, like you, fall in love with the flawed notion that their application is such a special snowflake that it deserves "advanced techniques". Bullshit. There are good techniques and bad techniques. Size of the application is rarely a factor, except in ballooning the ego of the programmer.
Anyway, the invitation stands. Present any piece of real code and we can ping pong on it. I enjoy talking about specifics and improving real code. I detest "oh that was just a poor example, but the general principle is..." kind of debates. If you can't produce a good example, you don't have a general principle.
And honestly, Rails already has something that works beautifully for an “interactor” extraction. It's called ActiveModel. Add a bit of other code (include ActiveModel::ForbiddenAttributesProtection, ActiveModel::Validations::Callbacks, and ActiveModel::SerializerSupport; extend ActiveModel::Naming) and you've got an object that acts like an ActiveRecord object but orchestrates changes across multiple models in a clean, constructive way—without introducing an entirely different way of working with your code.
I've done this at both places I've been doing Rails and it works at both cleaning up the models it orchestrates and keeping the business logic in the places where it belongs. I'm working actively to get rid of some of the Rails Fads that have come through and wreaked havoc on the current codebase (we've got Presenters and Commands and all sorts of other stuff that is just making the code harder to understand with little value).
There's a million ways to skin this particular cat, and claiming that “adult” Rails needs this particular gem or that particular way of writing code says a lot more about the person claiming it than the people who aren't following that particular fad.
The thing which Rails and DHH offer no guidance whatsoever is the separation of persistence from the domain model. The Active Record pattern is itself a conflation of those two things, so this is an opinionated choice, and I respect it as a sane default for a wide variety of applications. It works perfectly fine up to a certain scale but when the business logic reaches a certain complexity and the persistence logic reaches a certain complexity then it makes sense to separate them. A lot of proposed solutions might be overkill, but keep in mind that DHH and the company formerly known as 37signals specialize in minimalist software, so they combat this complexity from the UX down rather than conceiving architectures to support it. I agree with this philosophy insomuch as all else being equal, simpler is better, but the problem is that some applications are necessarily more complex than Basecamp, and sometimes we need more than what Rails provides out of the box. Convincing DHH of this is pointless because he doesn't have to deal with it and he has no incentive to understand anyone else's pain in this regard.
Everyone[1] needs a persistence layer and domain objects. That ActiveRecord is both ActiveModel and persistence is neither here nor there—and Rails 3 did a lot to making it possible to separate ActiveModel (domain object behaviour) and ActiveRecord (persistence layer behaviour) in a logical perspective so you can choose to persist differently than ActiveRecord does. Everyone needs some kind of controller. Everyone needs some kind of presentation layer. Aside from providing sane defaults for all of this, Rails doesn't try to dictate how your application is built.
The “more complex” architecture required for your application is unlikely to be a good fit for my application’s “more complex” architecture. For Rails to anoint one particular “more complex” architecture…is to fail anyone else who doesn’t need that architecture or would need something different. If you want to promote a particular type of architecture, there are ways: write an Engine; include generators. Give people guidance. Tell people why they want to use your particular architecture, but also tell them why they shouldn’t use it. If a lot of people need it, they will adopt it. Like Rspec. Like cucumber. Like ActiveModel::Serializers.
And, honestly, consider whether you really need your “more complex“ architecture or whether you can combat it the same way that Basecamp does. We're doing that with our product team, trying to find features we can remove and reimplement later when we really need them. Ours is a fairly mature product, so it's hard—but it's happening.
[1] For some large subset of everyone. Anyone who is reaching for something like Rails, Django, etc. needs some sort of persistence layer. Anyone who needs to store data needs that. Everyone needs domain objects.
But they're useful for dealing with side-effects of a particular operation too (sending multiple emails, notifying admins). Much better than ActiveRecord callbacks.
If you put this logic in the controller, what happens when you want a separate API controller that does the same thing? Or some admin functionality elsewhere in the codebase? There's zero possibility of code re-use.
Because when the reuse case actually arrives, you might find that you need to reuse some, but not all of the action. If you're literally doing the exact same thing for both web and api, why are you using a separate API controller? Just use respond_to with formats.
Second, yes, you shouldn't have side-effects like sending email in your models. But you don't need to! Just stick that logic in your controllers. That's what it's there for -- to render the views (of which emails is one of them -- see http://david.heinemeierhansson.com/2012/emails-are-views.htm...).
The AR callbacks are wonderful for coordinating the domain model. Often times you'll want to create auxiliary objects when something else is created. That's what's it's there for. Or to otherwise keep the integrity of the domain model in place.
This example is from a real-life codebase, and the interactor was extracted from 3 or 4 (bloated, repetitive) controllers. Perhaps this could have been made clearer in the post.
I'm not arguing at all that every controller needs an Interactor, or all Rails codebases should start out with Interactors present.
I am saying that Interactors are very useful concepts for re-using code, and that many medium and large Rails codebases could benefit from them.
Callbacks in Controllers and AR::Models tend to make things worse IMO for anything other than authentication; and for intricate actions interactors seem like the best defence.
I have had the (mis)fortune to jump into a number of large Rails codebases and I can say with hand-on-heart that the only ones that made any sense off-the-bat were ones using a this-or-similar pattern.
The community is embracing policies, interactors and decorators for a reason. Real developers are having real problems when Rails apps get a certain size, and there is no endorsed method on how to handle these problems.
Surely a couple of asides on the Rails docs and some official endorsement could help point new developers in the direction of a possible solution? A solution the industry already seems to be taking; regardless of whether 37Signals deems it fit for their particular domain.
No, they're not. They're great for coordinating activities around your database. That's not a domain model, unless your domain is databases. Conflating domain with database through the use of active record doesn't mean that structural models are domain driven, and events based around database interactions aren't going to be any more domain driven than the active record objects themselves.
You refactor.
In my experience, anytime you're writing something for the sake of "possible code re-use", you're wasting time. Code should and does get refactored often. By adding levels of indirection from the outset, you add a barrier to refactoring and likely additional unnecessary code.
YAGNI, and all that.
[1] http://www.amazon.com/Domain-Driven-Design-Tackling-Complexi...
In that same vein, this may be a repeat message of a concept that is not novel, but as an experienced non-web developer who is fairly new to Rails, I learned something from reading this.
I also appreciate you pointing out what sounds like a good development resource (Domain Driven Design).
The problem is that Rails ships with a very limited set of core architectural concepts, and many inexperienced Rails developers feel like they've got to cram all of their code into a Model, View or Controller.
Once your codebase reaches a certain complexity, principles from other programming paradigms are extremely useful.
The problem is that people think Rails is an architecture to begin with. Rails is just a framework that uses the MVC pattern (mangled slightly to fit the realm of HTTP). In the end, MVC is nothing but a directory structure for our files. What you put in those files and directories is up to you. Uncle Bob gave a great keynote on this called Architecture: The Lost Years. Here's a link: http://www.confreaks.com/videos/759-rubymidwest2011-keynote-...
In this way, we've successfully commoditized another differentiating factor of developers so we can ship on Internet Time(tm).
method confirm_grouper () {
MyApp::Action::ConfirmGrouper->new(leader => $self)
->run
}
and then the controller would simply do - my $result = $member->confirm_grouper;A Service Object work, could just echo hello world every 15 seconds and still be called a Service Object, while a model in your application doing the same thing can no longer be called a Model.
So you could cram every design pattern known to man and they would still cram everything in their controller.
API's are hard to discover and it takes time through trial and errors or being teached the way things are.
For beginners, I'm not sure it would be helpful to introduce a whole load of named patterns, as it just leads to cargo-culting and overuse of patterns without understanding whether they even apply.
It was interesting to read about a different approach though - thanks for the article.
The important metric here isn't "wc -l app/models/god.rb", it's "God.public_instance_methods.length".
[1] http://www.infoq.com/minibooks/domain-driven-design-quickly
Ruby and Rails feel best as a prototyping platform for getting something out the door fast, proving a concept, and not worrying so much about correctness or maintenance.
I don't think if you are doing a lot of TDD and larger systems that piling on more Ruby and Rails is the right answer. I think once you know what you are working with, a well designed language with a compiler is a huge help and would remove a ton of useless tests and stuff that you end up writing in Ruby by hand.
This very likely leads to an API driven system with an API written in a strongly typed, compiled language like C#, Java, Scala, Haskell, or Go and writing your front end in whatever makes the most sense for your team.
At that point you get the benefits of a nice rapid development platform like Rails for your front end, and a fast, testable, API written in something else using all the clean code architecture you want.
The trick is, you do everything ugly in Rails or PHP or whatever in your initial prototype and you might not even write tests. You just ship working code until your prototype has proven a business case. Then, you move it towards something with lower TCO over time. Make the investment in your code when it makes sense to invest in it and use the best tool for the job at each step.
You probably never need to leave the standard Rails MVC stuff on most projects unless they are wildly successful and/your long term needs change. Even then, you can probably keep the rails front end stuff and just talk to an API and be very happy.
Having worked with the Interactor gem for a little while once you break things down into small interactors that can be used by the Organizers, I have two main complaints.
1) inputs are unclear. With calling new or some custom class method you can use descriptive variable names to say what the object expects to be present to do it's job. With the Interactor gem you end up adding in comments describing what keys need be present in the context and what keys will be added to the context so the next programmer can use the interactor you've created without having to go through and grok everything.
2) You end up having to (re)create a failure protocol to communicate with the controller and display to the user. We take the AR errors functionality for granted in our controllers/views with interactors you have to come up with a similar system.
2.5) as a result you end up writing a lot of boilerplate fail! and rollback code
2.5.2) and a non-atomic operation like notifying the payment gateway can break the whole model of rolling back and you have to end up raising so your user doesn't end up in a invalid state or get charged twice.
We've got a convention that all Interactors must be commented to specify what inputs they take.
Responds in much the same way active record does, allowing validations, errors, forms built from interaction objects, etc.
You've got a God class that exposes 500+ public methods, so you split it into concerns. But now you've still got a God class with 500 methods that's split across 10 files. Good luck understanding that.
Concerns are useful when they're genuinely sharing functionality between classes - not just for splitting up "Big Bags O' Methods".
Hmmm. I'd say it depends.
Of course having concerns (a fancy word for modules IMHO) shared between classes is great. But i've also found cases where separating a god class' behaviour into different concerns helped a lot. The important thing in those cases was recognizing and avoiding dependencies between different concerns, so instead of ending up with a god class split across many files of inter-dependant code (i.e. worse than before), you can end up with a "god" class split into its minimal "core" part and a couple of concerns that only depend on that core part but not between each other. Yes, you could still call that a god class, as it will have a very fat public API, but at least you can reason about what it does in terms of different concerns, so you gain something :)
I've found them genuinely useful for that - there is a lot of code for things like urls, publish status, ratings, roles, permissions etc that can be shared between models if they have similar functionality.
They're just a recognition that composition via modules is often better than inheritance.
require 'active_support/concern'
require 'my_cool_concern'
class DummyClass
include MyCoolConcern
endOr, perhaps, to turn this argument around, it's better to say it this way: A Concern is poorly-constructed if it cannot be tested in isolation, so therefore something like MyCoolConcern should be written with its testability (inside of DummyClass) in mind.
Rails is easy to extend, people often forget that. Great post.
At MoneyBird we are using the Mutations gem to represent something like the interactors mentioned in this article. One major advantages of Mutations, is that is also does input filtering.
https://github.com/orgsync/active_interaction https://github.com/cypriss/mutations
0 - http://www.ruby-doc.org/stdlib-1.9.3/libdoc/delegate/rdoc/Si...
1 - http://www.ruby-doc.org/stdlib-1.9.3/libdoc/delegate/rdoc/De...
2 - http://www.ruby-doc.org/stdlib-2.0/libdoc/forwardable/rdoc/F...
MassivelyUpVotedPostPresenter.new(@post, self.view_context)
Or just inject the whole controller instance and you have your router helpers too!
MassivelyUpVotedPostPresenter.new(@post, self)
- Built-in ActiveModel validations. - Designed to be used with form objects. - Easier and more flexible composition. - Translatable with I18n. - Quacks like an ActiveModel.
That being said, Mutations is a great library for PORO interactors and ActiveInteraction wouldn't exist without it.
1) Use presenters for display-only logic to keep controllers concerned with managing requests only.
2) Using service object / custom classes in /lib for actions on models as well as abstracting any common related functionality. Creators, Updaters, Processors, Orchestrators, etc. Keep your models only concerned with data and not data transformation, and your controllers from doing it as well.
I created a flowchart that illustrates this strategy: http://rails-recipes.clearcove.ca/pages/how_to_change_object...
One of the future posts (coming soon!) will be on Presenters / Decorators.
I would argue these custom classes should still live in /app, rather than /lib, but I may be wrong.
> Here at Grouper, we’re long-time users of Ruby on Rails – along with other New York startups like RapGenius, Etsy and Kickstarter.
Etsy doesn't use Rails though, it uses PHP.
Maybe there are some "user" features (login, logout, change name) and "cart" features (add/remove item in cart).
These features would all live horizontally, be able to call each other (design your object graph wisely!) and would never be able to inspect or elaborate on implementation details!
These features may or may not talk to some database for its own persistence, but that's up to the functions.
And the features are pure functions in your language of choice. They have no knowledge of the web, or requests, they're perfectly transient. They act on a "state" object that you pass around to them, which in tests is just a blob of memory and in production is a real database or wherever else you store state.
It's simple, yet so powerful. This is how we do it, and it's scaling very nicely.
I think that the answer is clear, this should not be a part of rails since it's not true to all apps.
I think that if you want to have something real quick, you don't need an interactor/service class.
When you have a bigger app, you definitely need that, or you will get to a point where you code is split into models/observers/callbacks/lib/app/concerns and you can't find anything.
Rails generators are pretty easy to extend, this way, when you generate a new model, you can easily create the service class for it.
You can also EASILY create new generators that will generate the service classes for you with your defaults and templates and what not.
Not sure Rails is missing that, however, it is definitely a best practice that people with bigger apps should use TODAY.
The author describes different ways of refactoring fat ActiveRecord models, but most of the ideas can be used outside ActiveRecord, as "best practices".
I have been using some of the patterns described in it and I am really happy with the results. The code becomes more clearly decoupled, is easy to test and results in clean, slim models.
I wonder if he's ever worked with an app that has a complicated domain.
His comments taken from this perspective make a lot of sense. Rails was written for Basecamp.
For large apps with real complexity, the rails way falls short.
before_save can modify the state of other objects. It doesn't have to. One might use it to modify only the state of the current model. You are reaching a bit, blaming the callback, when what you are really concerned with is an awkward and potentially dangerous use of the callback.
interactor: https://github.com/collectiveidea/interactor wisper: https://github.com/krisleech/wisper
/lib is intended for non-app specific code. The halfway house before code is extracted into either a Rails PR or a separate gem.
/app/factories - for classes which create active record objects
/app/services - for classes which do something I generally don't care about the return value of. Often perfect for background jobs.
/app/decorators - most of these are Draper classes
/app/forms - form objects
and a few others from various other gems. /app/interactors
It's a trivial thing to add new folders like this to autoloading: # add to application.rb
config.autoload_paths += %W(#{config.root}/app/interactors)* https://github.com/rails/rails/blob/3-0-stable/railties/test...
Anything that's generic and re-usable, we put in /lib. This code is normally a prime candidate for gems - only very simple code stays in /lib for very long.
http://blog.arkency.com/2014/02/rails-refactoring-the-aha-mo...
The second missing part: Ruby is Rails. Trying to learn Ruby at the same time as a modern web framework with all its moving parts? Forget it.
The third missing part: Tutorials. Okay, I haven't done a rant on this. Google rails tutorial. The first helpful result I get [2], I scroll down. The first meat is "Setting the application home page". I see this:
Blog::Application.routes.draw do
get "welcome/index"
Huh? "This is your application's routing file which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions." So it's not even Ruby or some recognized Web glue language like HTML or CSS; it's some domain-specific language? Okay, I totally don't get it, so as suggested, for more details, I should refer to "Rails Routing from the Outside In" [3].This is even more confusing. It says you should do something like this:
get '/patients/:id', to: 'patients#show'
Huh? What's the deal with the colons and octothorpe? I can guess colon is the signifier for an ID in the URL, but why the pound sign for #show? get '/patients/:id', to: 'patients#show', as: 'patient'
And what's the deal with the colons?I could go on and on. I'm sure that with a few hours of pain and frustration, I would be able to figure out exactly all the oddities of Ruby syntax, or the template language, or the DSL whatever, and understand this example well enough to extend it.
But that's not the point. The point is that, because I have to spend those hours, it means that Ruby/Rails is poorly designed. In Django, by contrast, things are almost always simple and obvious.
[1] https://news.ycombinator.com/item?id=5872899
'#' is the standard notation used throughout the Ruby language for instance methods.
Think of it like this:
Blog::Application.routes.draw do |implicit_self|
implicit_self.get( '/patients/:id', { to: 'patients#show', as: 'patient' } )
endWhy isn't it "call" so it can be swapped out with a lambda, or method reference without hassle?
Services should be run with call.
-- spike@etsy.com