Random 'concerns' folders and '.keep' files

后端 未结 3 828
野趣味
野趣味 2020-12-05 12:42

I am learning rails.

Somewhere along the line, I noticed that seemingly random folders and files are appearing in my rails app\'s directory. In some folders there i

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 13:00

    Concerns is a simple but powerful concept. It exists for code reusability. Basically, the idea is to extract common and / or context specific chunks of code in order to clean up the models and avoid them getting too fat and unmanageable.

    I would like to specify explicitly that you should use service objects to provide functionality that's not the concern of the specific object. Eg a organisation has many users. Now the admin of organisation needs to export a CSV of all users for this organisation. This code can be placed in organisation model but since its not the responsibility of the organisation object, this code should be placed in a class where u just pass the organisation object and it returns the CSV of all users.

     class Services::GenerateCsv
         def self.get_users org
             #add logic the fetch users for the org and generate the CSV and return the CSV data
         end
     end
    

    Whenever you need CSV generation, u can place to that logic in the above class. This approach keeps the object (in this case, the organisation model) clean from the code that shouldn't be its responsibility. A general principle that I follow is: if the code it's modifying the self object, move the code to a service object.

    Note: Your question was regarding concerns but I thought of adding some extra stuff that I follow to keep the code base clean and manageable since it might help fellow programmers. That above approach is debatable.

提交回复
热议问题