Concerns, Decorators, Presenters, Service Objects,

2020-05-20 08:56发布

There are few things in Rails:

## Concerns
## Decorators
## Presenters 
## Service Objects
## Helpers

Can anybody give me real problem example in what type of situation what should I follow, So I can have better understanding of these features.

Examples will be better to understand the concept

Thanks in advance and thanks for looking

2条回答
够拽才男人
2楼-- · 2020-05-20 09:48

Concerns

Are used to share functionality between files in one 'type' ('model', 'controller', ...). Thus you have

  /app
    /controllers
       /concerns

    /models
       /concerns

In concerns you put modules which will be included inside classes. It is god practice to put some behaviour code. For example

/app
  /models
    /concerns
       messageable.rb
    project.rb
    ..
    proposal.rb

Project model

class Project < ActiveRecord::Base
  include Messageable
end

Proposal model

class Proposal < ActiveRecord::Base
  include Messageable
end

inside app/models/concerns/messageable.rb

require 'active_record/concern'
module Messageable
  extend ActiveSupport::Concern

  # implement behaviour
  module ClassMethods
     # class methods for the behaviour
  end
end
查看更多
Summer. ? 凉城
3楼-- · 2020-05-20 09:52

Well, as I said in the comment, you'll be better of with simple google searches.

For example, this is a nice article about most of them.

I'll just walk you through the basics.

  1. Concerns are mainly for DRYing up your models and controllers. If you have a very fat controller/model that has lots of functionality in it (violating the SRP), it's much better to break it into several independant concerns and just include them back in. That way you can also share functionality between similar controllers/models. Here's a nice article.

  2. Decorators are used for separating models' business logic with their user appearance. E.g. for storing methods only used in the views and for other displaying. They are also used to extend the logic of an object. Here is a nice thoughbot post.

  3. Presenters are practically the same, but used only for displaying purposes.

  4. Service Objects are mainly used for sophisticated logic that does not necesserally belong in a specific model/controller and/or deals with several models for example.

  5. Helpers are solidly for moving logic out of the view and thus simplifying the view patterns and DRYing up the views. Usually used for simple things ('cause otherwise it's better to use a decorator or a presenter).

查看更多
登录 后发表回答