Last Updated: February 25, 2016
·
1.375K
· boriscy

SimpleDelegator Query Objects and Param Objecs

Applications get complicated and in the old times I used to put all my logic in the model, don't do that learn the Single responsability principle use Query objects, Params Objects, etc. For example you have the User and you want to put related logic to the User class in some place this is why I generally create a folder app/models/users and store related logic to the User there with many objects for example a query object

module Users
  class Query < SimpleDelegator
    def initialize(rel = nil)
       rel = User  if rel.nil?
       super(rel)
    end

    # In some cases you must use the __getobj__ method
    def select_simple
       __getobj__.select('email, first_name')
    end

    # You can use most of the time all User methods but in some case you will have to use
    # __getobj__ for example for select method
    def complex_query(search_params={})
       params = Users::SearchParams.new(params) # This line can be improved
       joins(:another_model).where(inscription_date: params.date_start)....
    end
    #...
  end
end

You can really improve Query Objects with Param Objects for example you want to do a search and you receive some params as startdate, enddate and search

class Users::SearchParams
   attr_reader :start_date, :end_date, search

   def initialize(attrs = {})
      @start_date = get_parsed_date(attrs[:start_date])
      @end_date = get_parsed_date(attrs[:end_date])
      @search = search_value(attrs[:search])
   end

   def date_range
      date_start..date_end
   end

   private

     def get_parsed_date(d)
        Date.parse(d)
     rescue
        Date.today
     end

    def search_value(s = nil)
       s.nil? ? 'default value' : s
    end
end

Of course then you can use this Users::SearchParams in your query objects or in other places where you need, in this way you keep your clases cleaner.

1 Response
Add your response

excellent, I was a great help thanks

over 1 year ago ·