A collection of lightweight, standardized, rails-oriented patterns.
A collection of lightweight, standardized, rails-oriented patterns.
A collection of lightweight, standardized, rails-oriented patterns used by RubyOnRails Developers @ Selleo
# Gemfile
#...
gem "rails-patterns"
#...Then bundle install
One should consider using query objects pattern when in need to perform complex querying on active record relation. Usually one should avoid using scopes for such purpose. As a rule of thumb, if scope interacts with more than one column and/or joins in other tables, it should be moved to query object. Also whenever a chain of scopes is to be used, one should consider using query object too. Some more information on using query objects can be found in this article.
.call methodActiveRecord::Relation or ActiveRecord::Base as constructor argumentqueries macro#query method that returns ActiveRecord::Relation#options hashBecause of the fact, that QueryObject implements .call method, those can be used to construct scopes if required. (read more...)
class RecentlyActivatedUsersQuery < Patterns::Query
queries User
private
def query
relation.active.where(activated_at: date_range)
end
def date_range
options.fetch(:date_range, default_date_range)
end
def default_date_range
Date.yesterday.beginning_of_day..Date.today.end_of_day
end
endRecentlyActivatedUsersQuery.call
RecentlyActivatedUsersQuery.call(User.without_test_users)
RecentlyActivatedUsersQuery.call(date_range: Date.today.beginning_of_day..Date.today.end_of_day)
RecentlyActivatedUsersQuery.call(User.without_test_users, date_range: Date.today.beginning_of_day..Date.today.end_of_day)
class User < ApplicationRecord
scope :recently_activated, RecentlyActivatedUsersQuery
endService objects are commonly used to mitigate problems with model callbacks that interact with external classes (read more...). Service objects are also useful for handling processes involving multiple steps. E.g. a controller that performs more than one operation on its subject (usually a model instance) is a possible candidate for Extract ServiceObject (or Extract FormObject) refactoring. In many cases service object can be used as scaffolding for replace method with object refactoring. Some more information on using services can be found in this article.
.call method#call method.call method executes #call and returns service object instance#call method is accessible through #result method#call method to be the only public method of service object (besides state readers)ActivateUser instead of UserActivation)A bit higher level of abstraction is provided by business_process gem.
class ActivateUser < Patterns::Service
def initialize(user)
@user = user
end
def call
user.activate!
NotificationsMailer.user_activation_notification(user).deliver_now
user
end
private
attr_reader :user
end user_activation = ActivateUser.call(user)
user_activation.result # <User id: 5803143, email: "tony@patterns.dev ...One should consider using collection pattern when in need to add a method that relates to the collection a whole.
Popular example for such situation is for paginated collections, where for instance #current_page getter makes sense only in collection context.
Also collections can be used as a container for mapping or grouping logic (especially if the mapping is not 1-1 in terms of size).
Collection might also act as a replacement for models not inheriting from ActiveRecord::Base (e.g. StatusesCollection, ColorsCollection etc.).
What is more, collections can be used if we need to encapsulate "flagging" logic - for instance if we need to render a separator element between collection elements based on some specific logic, we can move this logic from view layer to collection and yield an additional flag to control rendering in view.
Enumerable.new, .from and .for (aliases)#collection method that returns object responding to #each#options hash#subjectclass ColorsCollection < Patterns::Collection
AVAILABLE_COLORS = { red: "#FF0000", green: "#00FF00", blue: "#0000FF" }
private
def collection
AVAILABLE_COLORS
end
end
class CustomerEventsByTypeCollection < Patterns::Collection
private
def collection
subject.
events.
group_by(&:type).
transform_values{ |events| events.map{ |e| e.public_send(options.fetch(:label_method, "description")) }}
end
endColorsCollection.new
CustomerEventsByTypeCollection.for(customer)
CustomerEventsByTypeCollection.for(customer, label_method: "name")Form objects, just like service objects, are commonly used to mitigate problems with model callbacks that interact with external classes (read more...).
Form objects can also be used as replacement for ActionController::StrongParameters strategy, as all writable attributes are re-defined within each form.
Finally form objects can be used as wrappers for virtual (with no model representation) or composite (saving multiple models at once) resources.
In the latter case this may act as replacement for ActiveRecord::NestedAttributes.
In some cases FormObject can be used as scaffolding for replace method with object refactoring. Some more information on using form objects can be found in this article.
ActiveModel::Validations to support validation.Virtus.model to support attribute static method with all corresponding capabilities..new.#persist method that returns falsey (if failed) or truthy (if succeeded) value.#resource.#save or #save! methods.resource#attributes and public getters for resource#as builder method that populates internal @form_owner variable (can be used to store current user).#param_key method result by using .param_key static method. This defaults to #resource#model_name#param_key.#persisted? method to #resource if possible.ActionController::Parameters as attributes hash (using to_unsafe_h)#persist method in transaction if possible and if multiple model are affected.…form = UserForm.new(User.find(1), params[:person])
form.save
form = UserForm.new(User.new, params[:person]).as(current_user)
form.save!
ReportConfigurationForm.new
ReportConfigurationForm.new({ include_extra_data: true, dump_as_csv: true })Calculation objects provide a place to calculate simple values (i.e. numeric, arrays, hashes), especially when calculations require interacting with multiple classes, and thus do not fit into any particular one. Calculation objects also provide simple abstraction for caching their results.
#result method that returns any value (result of calculation)..set_cache_expiry_every method, that allows defining caching period..set_cache_expiry_every is not used, result is not being cached..calculate, .result_for or .result.#subject private method.#options private method.#cache_key of each argument value is used if possible.Rails.cache is used as cache store.class AverageHotelDailyRevenue < Patterns::Calculation
set_cache_expiry_every 1.day
private
def result
reservations.sum(:price) / days_in_year
end
def reservations
Reservation.where(
date: (beginning_of_year..end_of_year),
hotel_id: subject.id
)
end
def days_in_year
end_of_year.yday
end
def year
options.fetch(:year, Date.current.year)
end
def beginning_of_year
Date.new(year).beginning_of_year
end
def end_of_year
Date.new(year).end_of_year
end
endhotel = Hotel.find(123)
AverageHotelDailyRevenue.result_for(hotel)
AverageHotelDailyRevenue.result_for(hotel, year: 2015)
TotalCurrentRevenue.calculate
AverageDailyRevenue.resultRule objects provide a place for dislocating/extracting conditional logic.
Use it when:
#satisfied?, #applicable?, #not_applicable? and #forceable? methods available.No open issues yet, or sync has not completed.