Every now and them I would come across this in the ruby on rails ecosystem:
class LocalizeUrlService
class Services::UpdateUserRegistrationForOrder
class ProductionOrderEmailService
UserCart::PromotionsService.new(
Shipping::BulkTrackingService.new(bulk_update, current_spree_user)
You can also see an example here
However, in the official examples of for example "Ruby On Rails Guides" I've never seen this. Which leads me to believe this is a concept coming from another language/paradigm different to Rails/OOP.
Where is this paradigm/trend coming from? Is there a tutorial/book
that these folks got influenced by? Are these folks holdouts from the SOA trend of a few years ago?
Is it a good idea to put code in app/service/blah_service.rb ?
If yes, what logic/code can be considered "Service" material.
Is there any kind code that would/wouldnt belong as a service?
What gem/plugin creates the app/services folder? The vanilla rails app doesn't ship with it at first.
sidetone: Personally I have issue with instantiating a service. I feel classes and instantiating is misused by a ametuer programmers. I feel a class and instantiating is "for a thing" and a service is something that "does"
so mixins/defs/include should be the way to go I feel.
Service objects are for things that don't fit well in the normal MVC paradigm. They're typically for business logic that would otherwise make your models or controllers too fat. Typically they have no state (that's held in a model) and do things like speak to APIs or other business logic. Service objects let you keep your models thin and focused, and each service object is also thin and focused on doing one thing.
Rails Service Objects: A Comprehensive Guide has examples of using service objects to manage talking to Twitter, or encapsulating complex database transactions which might cross multiple models.
Service Objects in Ruby on Rails…and you shows creating a service object to manage the new user registration process.
The EngineYard blog posted Using Services to Keep Your Rails Controllers Clean and DRY with an example of a service object which does credit card processing.
If you're looking for the origins, Service objects in Rails will help you design clean and maintainable code. Here's how. is from 2014 when they were coming on the scene.
Services has the benefit of concentrating the core logic of the application in a separate object, instead of scattering it around controllers and models.
The common characteristic among all services is their lifecycle:
accept input
perform work
return result
If this sounds an awful lot like what a function does, you're right! They even go so far as to recommend using call as the public method name on the service, just like a Proc. You can think of service objects as a way to name and organize what would otherwise be a big subroutine.
Anatomy of a Rails Service Object addresses the difference between a service object and a concern. It covers the advantages a service object has over modules. It goes into some detail about what makes a good service object including...
Do not store state
Use instance methods, not class methods
There should be very few public methods
Method parameters should be value objects, either to be operated on or needed as input
Methods should return rich result objects and not booleans
Dependent service objects should be accessible via private methods, and created either in the constructor or lazily
For example, if you have an application which subscribes users to lists that might be three models: User, List, Subscription.
class List
has_many :subscriptions
has_many :users, through: :subscriptions
end
class User
has_many :subscriptions
has_many :lists, through: :subscriptions
end
class Subscription
belongs_to :user
belongs_to :list
end
The process of adding and removing users to and from lists is easy enough with the basic create and destroy methods and associations and maybe a few callbacks.
Now your boss wants an elaborate subscription process that does extensive logging, tracks statistics, sends notifications to Slack and Twitter, sends emails, does extensive validations... now what was a simple create and destroy becomes a complex workflow contacting APIs and updating multiple models.
You could write those all as concerns or modules, include all that stuff into these three formerly simple models, and write big Subscription.register and Subscription.remove class methods. Now your subscriptions can Tweet and post to Slack and verify email addresses and perform background checks? Weird. Your models are now bloated with code unrelated to their core functionality.
Instead you can write SubscriptionRegistration and SubscriptionRemove service objects. These can include the ability to Tweet and store statistics and perform background checks and so on (or more likely put that into more service objects). They each have one public method: SubscriptionRegistration.perform(user, list) and SubscriptionRemove.perform(subscription). User, List, and Subscription don't need to know anything about it. Your models stay slim and do one thing. And each of your service objects do one thing.
As to your specific questions...
Where is this paradigm/trend coming from?
As near as I can tell, it's a consequence of the "fat model / skinny controller" trend; that's how I came to it. While that's a good idea, often your models get TOO fat. Even with modules and concerns, it gets to be too much to cram into a single class. That other business logic which would normally bloat a model or controller goes into service objects.
What gem/plugin creates the app/services folder?
You do. Everything in app/ is autoloaded in Rails 5.
Related
So I am a fairly seasoned Django developer and I've been using Ruby on Rails for about a year. I'm working on a project with, let's say, 100 models. In my actual scenario, I'm writing a "component" to the app, which requires 2 models, one of which I wanted to call Event, however there is another piece of the software which uses an Event model in a totally different context. In Django, this is resolved by splitting the "components" into "apps", and models can have the same name because they are in a different app.
Is there is a similar pattern in Rails to separate some models in their own package to avoid name conflicts, but also so that each separate component can have it's own README which describes how that component behaves? I don't require that it have it's own controllers/views, since right now we have a single frontend interface, but I would be interested to hear if there is a pattern for that too. I've heard the term "engines" in Rails, but that seems to imply a total decoupling and unidirectional dependency scheme like for a generic 3rd party app, where as in my case, there is still some coupling between this "component" and the rest of the app, but it still seems reasonable to have some way of grouping models logically.
Also, I'm wondering how this case is handled in general. When a web application grows organically to have tons and tons of models, is there a standard pattern for managing this complexity?
You can use namespacing using modules for your models.
For example Foo::Bar or Baz::Bar like this:
module Foo
class Bar < ApplicationRecord
end
end
To associate this model with table foo_bars, you can implement the method:
module Foo
class << self
def table_name_prefix
'foo_'
end
end
end
I'm developing a web app that has several "subapps" inside it. For some of them a RDBMS is clearly the weapon of choice. The issue is that lately I came with an idea for a nice little subapp whose logic and performance would benefit greatly from using a graph based database.
My problem is: This subapp is important and graph is the way to make it happen. On the other hand, the others are just fine on a RDBMS and in some cases migrating them to graph would add unnecessary complexity.
So, is it possible to have two heterogeneous database systems running on the same Rails app, perhaps using each controller to specify where to connect?
This is absolutely possible, but it's not something you'd handle at a controller level: it is the responsibility of each model class to define how its data is stored, for example by subclassing from ActiveRecord::Base or including Mongoid::Document or Neo4j::ActiveNode.
There's nothing particular you need to do. As long as the objects all conform to the active model interface (the above all do) then things like link_to 'Person', #person will still work.
I'm very interested to see what Rails veterans on Stack Overflow have to say about this.
Basically, as a Rails newb, and as someone with no "formal" background in programming, one of my biggest challenges has to do with proper architecture. How do I know what the right or better to build an app are?
I would love to see what some resources are.
I know the basic ones - but a lot of these don't give me the high level architecture overview I want:
http://www.amazon.com/Agile-Development-Rails-Third-Edition/dp/1934356166/ref=cm_lmf_tit_7
http://www.amazon.com/Ruby-Programming-Language-David-Flanagan/dp/0596516177/ref=cm_lmf_tit_3
Railscasts
Here's a quick example:
Say I'm building a Rails app that has merchants and shoppers - each set of users has its own authentication, different permissions, etc. Would it be proper to build a single app for this or multiple that communicate through APIs? Is there any added benefit to this multi-app abstraction?
Thanks!
this is not an easy question. The complete answer would largely depend on your project.
If you are a starter I'd recommend you keep it all in one app, you have enough "separation" using models wisely. It's hard to immagine a scenario where the complexity introduced by inter-app communication is beneficial.
In your example you should ask yourself wether it's better to use one single parent model for the Merchants and Shoppers or two separate models.
In the former case you can consider STI:
user (main class, defined as class User < ActiveRecord::Base)
merchant (defined as class Merchant < User)
shopper (similarly class Shopper < User)
Google for STI for further details.
Then in your controllers/view you can check permissions quickly, for example:
if user.class == Merchant
do_something
else
do_something_else
end
Similarly the two classes might authenticate with different algorithms. You might also include a "standard" authentication in the base User class and specialize it in the subclasses, if required.
Cheers,
I am designing a CRM using Ruby on Rails. How do you think, do I need a separate database for every client company? Or should I use the same database for everyone?
If they are separate companies or competing companies (for say a white label CRM) you'll most definitely want to run separate instances because then you can credibly claim total sandboxing. Otherwise, if you ever inadvertently wrote code that somehow allowed the data from one to display for the other, the game is over. Your customer will run for the hills and tell everyone about their terrible experience with your product.
I would even suggest you run separate instances of your app for each customer. Heroku provides a super simple way to deploy RoR apps so spinning up a new one whenever you add a new customer is a reasonable approach. Of course, if you want a more turnkey solution that allows people to just sign up for an account, you will have to have a single instance that enforces customer data sandboxing in code. Obviously it can be done, but the separation isn't done at the infrastructure level which is ultimately the safest way.
Best regards.
I do it with a single database, like this:
class Company < ActiveRecord::Base
has_many :records
def recent_records
records.desc(:created_at)
end
end
class Record < ActiveRecord::Base
belongs_to :company
end
Then, in the controller, I can write:
#records = #company.recent_records
And pass that down to the views.
Hope this helps.
I'm building a Rails app that is probably going to have a large amount of models. For now let's say that i need to have Users, and each User will have a personal Blog
I've been developing the User-related part on a separate Engine (let's call it AuthEngine) that encapsulates the User model, authentication, etc. At the time this seemed like the best approach
In parallel, my colleague was developing another engine, to deal with the blog features (let's call it BlogEngine).
Now he needs to access user data which is stored in the other engine. He achieved this by defining:
BlogEngine.user_class = "AuthEngine::User"
This way, he can easily ask for user data, even though it isn't stored in the same engine. The problem comes when we want to define relashionships between models
He can easily say that each blog post belongs to a user
has_one :user, :class_name => BlogEngine.user_class
But as far as i know he can't specify that each User has multiple posts since the User model is within the other engine
The consequence of this is that he can't do things like #user.posts, but instead has to do Post.find_all_by_user(#user)
Is there a more elegant way to deal with this?
I also considered the possibility that each engine could simply generate the models inside the app, removing the encapsulation, but since the amount of models will grow quickly, i think this will make the app more of a mess, and not as much maintanable
I think you should reopen user class inside blog_engine in order to define has_many :posts relation and it should be appropriate way.
What about having a common models gem/engine with only the relationships as a dependency for your engines? This way you would have access to all relevant relationships in every engine.