Skip to content

Instantly share code, notes, and snippets.

@kopylovvlad
Last active June 22, 2018 15:14
Show Gist options
  • Save kopylovvlad/ae119b62b1435717b4ae976260019f2b to your computer and use it in GitHub Desktop.
Save kopylovvlad/ae119b62b1435717b4ae976260019f2b 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 create(params)
params = params
.merge(agreement: true)
.merge(capitalize_fio(params))
item = User.new(params)
if item.valid? and item.save
[true, item]
else
[false, item]
end
end
def update(user_id, params)
user = User.find(user_id)
params = params.merge(capitalize_fio(params))
if user.update(params)
[true, user]
else
[false, user]
end
end
private
def capitalize_fio(params)
{
name: capitalize_string(params['name'] || params[:name]),
lastname: capitalize_string(params['lastname'] || params[:lastname]),
patronymic: capitalize_string(params['patronymic'] || params[:patronymic]),
}
end
def capitalize_string(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
answer, @item = UserMutator.new.create(item_params)
if answer == true
render :show
else
return render_json_errors @item.errors
end
end
def update
answer, @item = UserMutator.new.update(params[:id], item_params)
if answer == true
render :show
else
render_json_errors @item.errors
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