Skip to content

Instantly share code, notes, and snippets.

@inem
Forked from kopylovvlad/model_refactoring.rb
Last active June 22, 2018 15:47
Show Gist options
  • Save inem/29d45abb5438b04cf67353199ce1653f to your computer and use it in GitHub Desktop.
Save inem/29d45abb5438b04cf67353199ce1653f to your computer and use it in GitHub Desktop.
# before (legacy model)
# app/models/user.rb
class User < ActiveRecord::Base
validates :name, length: { maximum: 100 }
validates :lastname, length: { maximum: 100 }
validates :patronymic, length: { maximum: 100 }
before_save :capitalize_name!, :if => :name_process_needed?
private
def name_process_needed?
name_changed? || lastname_changed? || patronymic_changed?
end
def capitalize_name!
self.name = capitalize_string(self.name) if( name_changed? && !self.name.blank? )
self.lastname = capitalize_string(self.lastname) if( lastname_changed? && !self.lastname.blank? )
self.patronymic = capitalize_string(self.patronymic) if( patronymic_changed? && !self.patronymic.blank?)
end
def capitalize_string str
new_str = str.slice(0,1).mb_chars.capitalize + str.slice(1..-1).mb_chars.downcase
new_str.to_s
end
end
# after
# app/models/user.rb
class User < ActiveRecord::Base
validates :name, length: { maximum: 100 }
validates :lastname, length: { maximum: 100 }
validates :patronymic, length: { maximum: 100 }
end
# app/mutators/user_mutator.rb
class UserMutator
def self.create(params)
params = params
.merge(agreement: true)
.merge(capitalize_fio(params))
item = User.new(params)
item.save
item
end
def self.update(user_id, params)
user = User.find(user_id)
params = params.merge(capitalize_fio(params))
user.update(params)
user
end
# params['name'] || params[:name] - it looks like unsolved problem outside
def self.capitalize_fio(params)
{
name: StringOperations.my_capitalize(params[:name]),
lastname: StringOperations.my_capitalize(params[:lastname]),
patronymic: StringOperations.my_capitalize(params[:patronymic]),
}
end
end
#lib/string_oprations.rb
module StringOperations
def my_capitalize(str)
return '' if str.nil? or str.size.zero?
str.slice(0, 1).mb_chars.capitalize + str.slice(1..-1).mb_chars.downcase
end
end
# app/controllers/admin/api/users_controller.rb
module Admin
module Api
class UsersController < AdminController
def create
@item = UserMutator.create(item_params)
if @item.errors
return render_json_errors @item.errors
else
render :show
end
end
def update
@item = UserMutator.update(params[:id], item_params)
if @item.errors.empty?
render_json_errors @item.errors
else
render :show
end
end
private
def item_params
params.require(:users).permit(
:role_id, :name, :lastname, :patronymic, :email, :password,
:password_confirmation
)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment