Skip to content

Instantly share code, notes, and snippets.

@jusk02
Last active April 24, 2017 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jusk02/26de6b5b74f7dba7da326ed1033192e2 to your computer and use it in GitHub Desktop.
Save jusk02/26de6b5b74f7dba7da326ed1033192e2 to your computer and use it in GitHub Desktop.
class Avatar
include ActiveModel::Model
# include ActiveModel::Serializers::JSON
include ActiveModel::AttributeMethods
include ActiveModel::Dirty
# include ActiveModel::Validations
def get_avatar(avatar_url,access_token)
@avatar_clean = ApiConecction.get("#{avatar_url}",access_token)
// aqui deberia tomar @avatar_clean.response_body y convertirlo en la imagen, pero no se que hacer
end
def update_avatar(file,access_token)
p file.size
response = ApiConecction.post("/Archivos/uploadAvatar",{:file => File.new(file.path , "rb"), :multipart => true} ,access_token)
return cont = JSON.parse(response.response_body)['url']
end
end
class Profile
include ActiveModel::Model
# include ActiveModel::Serializers::JSON
include ActiveModel::AttributeMethods
include ActiveModel::Dirty
# include ActiveModel::Validations
def initialize(params= {})
@avatar = params['avatar']
@id = params['id']
@usuarioId = params['usuarioId']
@nombres = apply_object(params['nombres'], "Nombre")
@nombres_id_ant = @nombres.id
@estadosCiviles = apply_object(params['estadosCiviles'], "EstadoCivil")
@estadosCiviles_id_ant = @estadosCiviles.id
@datosGenerales = apply_object(params['datosGenerales'], "DatoGeneral")
@datosGenerales_id_ant = @datosGenerales.id
@datosNacimiento = apply_object(params['datosNacimiento'], "DatoNacimiento")
@datosNacimiento_id_ant = @datosNacimiento.id
@nacionalidades = apply_object(params['nacionalidades'], "Nacionalidad")
@nacionalidades_id_ant = @nacionalidades.id
@direcciones = apply_object(params['direcciones'], "Direccion")
@direcciones_id_ant = @direcciones.id
@identificaciones = apply_object(params['identificaciones'], "Identificacion")
@identificaciones_id_ant = @identificaciones.id
@entidadesPrestadorasSalud = apply_object(params['entidadesPrestadorasSalud'], "EntidadPrestadoraSalud")
@entidadesPrestadorasSalud_id_ant = @entidadesPrestadorasSalud.id
# @errors = ActiveModel::Errors.new(self)
end
define_attribute_methods :avatar, :id, :usuarioId, :nombres, :estadosCiviles,
:datosGenerales, :datosNacimiento, :nacionalidades,
:direcciones, :identificaciones,
:entidadesPrestadorasSalud
# #for :Serializers:JSON
# def attributes
# {'id' => id, 'nombres' => nombres}
# end
# asigna los atributos tipo objeto de la clase profile que envian en la instancia (initialize)
# recibe la clase del objeto y el hash de datos de los atributos del objeto
def apply_object(array, klass)
# se convierte el string con el nombre de la clase a la constante clase para que pueda llamar los métodos
klass = Object.const_get(klass)
return klass.new if array.empty?
hash = array.last
klass.new(hash)
end
# inicio set y get attributes -necesarios para ActiveModel:Dirty self.changed
def avatar=(val)
avatar_will_change! unless val == @avatar
@avatar = val
end
def nombres=(val)
val.each do |k, v|
# si alguno de los valores de nombres cambia ejecuta nombres_will_change! que identifica que ese atributo cambio de valor
if @nombres.send(k.to_s) != val[k]
nombres_will_change! unless @nombres.send(k.to_s).nil? && val[k].empty?
break
end
end
val[:perfilId] = @id
@nombres = @nombres.assign_params(val)
end
def estadosCiviles=(val)
val.each do |k, v|
# si alguno de los valores de estadosCiviles cambia ejecuta estadosCiviles_will_change! que identifica que ese atributo cambio de valor
if @estadosCiviles.send(k.to_s) != val[k]
estadosCiviles_will_change! unless @estadosCiviles.send(k.to_s).nil? && val[k].empty?
break
end
end
val[:perfilId] = @id
@estadosCiviles = @estadosCiviles.assign_params(val)
end
def datosGenerales=(val)
val.each do |k, v|
# si alguno de los valores de datosGenerales cambia ejecuta datosGenerales_will_change! que identifica que ese atributo cambio de valor
if @datosGenerales.send(k.to_s) != val[k]
datosGenerales_will_change! unless @datosGenerales.send(k.to_s).nil? && val[k].empty?
break
end
end
val[:perfilId] = @id
@datosGenerales = @datosGenerales.assign_params(val)
end
def datosNacimiento=(val)
val.each do |k,v|
# si alguno de los valores de datosNacimiento cambia ejecuta datosNacimiento_will_change! que identifica que ese atributo cambio de valor
if @datosNacimiento.send(k.to_s) != val[k]
datosNacimiento_will_change! unless @datosNacimiento.send(k.to_s).nil? && val[k].empty?
break
end
end
val[:perfilId] = @id
@datosNacimiento = @datosNacimiento.assign_params(val)
end
def nacionalidades=(val)
val.each do |k,v|
# si alguno de los valores de nacionalidades cambia ejecuta nacionalidades_will_change! que identifica que ese atributo cambio de valor
if @nacionalidades.send(k.to_s) != val[k]
nacionalidades_will_change! unless @nacionalidades.send(k.to_s).nil? && val[k].empty?
break
end
end
val[:perfilId] = @id
@nacionalidades = @nacionalidades.assign_params(val)
end
def direcciones=(val)
val.each do |k,v|
# si alguno de los valores de direcciones cambia ejecuta direcciones_will_change! que identifica que ese atributo cambio de valor
if @direcciones.send(k.to_s) != val[k]
direcciones_will_change! unless @direcciones.send(k.to_s).nil? && val[k].empty?
break
end
end
val[:perfilId] = @id
@direcciones = @direcciones.assign_params(val)
end
def identificaciones=(val)
val.each do |k,v|
# si alguno de los valores de identificaciones cambia ejecuta identificaciones_will_change! que identifica que ese atributo cambio de valor
if @identificaciones.send(k.to_s) != val[k]
identificaciones_will_change! unless @identificaciones.send(k.to_s).nil? && val[k].empty?
break
end
end
val[:perfilId] = @id
@identificaciones = @identificaciones.assign_params(val)
end
def entidadesPrestadorasSalud=(val)
val.each do |k,v|
# si alguno de los valores de entidadesPrestadorasSalud cambia ejecuta entidadesPrestadorasSalud_will_change! que identifica que ese atributo cambio de valor
if @entidadesPrestadorasSalud.send(k.to_s) != val[k]
entidadesPrestadorasSalud_will_change! unless @entidadesPrestadorasSalud.send(k.to_s).nil? && val[k].empty?
end
end
val[:perfilId] = @id
@entidadesPrestadorasSalud = @entidadesPrestadorasSalud.assign_params(val)
end
def id
@id
end
def userId
@usuarioId
end
def avatar
@avatar_clean = Avatar.new
@avatar_response = @avatar_clean.get_avatar(@avatar, @@my_token)
end
def nombres
@nombres
end
def estadosCiviles
@estadosCiviles
end
def datosNacimiento
@datosNacimiento
end
def datosGenerales
@datosGenerales
end
def nacionalidades
@nacionalidades
end
def direcciones
@direcciones
end
def identificaciones
@identificaciones
end
def entidadesPrestadorasSalud
@entidadesPrestadorasSalud
end
# fin -necesarios para ActiveModel:Dirty self.changed-
def nombrescompletos
"#{nombres.primerNombre} #{nombres.segundoNombre} #{nombres.primerApellido} #{nombres.segundoApellido}"
end
def nombrecorto
"#{self.nombres.primerNombre} #{self.nombres.segundoNombre}"
end
#calculo de edad del perfil
def age
now = Time.now.utc.to_date
date_born = self.datosNacimiento.fechaNacimiento
return 0 unless date_born.present?
date_born = DateTime.parse date_born
now.year - date_born.year - ((now.month > date_born.month || (now.month == date_born.month && now.day >= date_born.day)) ? 0 : 1)
end
#inicio -necesarios para nested form-
def nombres_attributes=(attributes)
@nombres ||= {}
@nombres = Nombre.new(attributes)
end
def estadosCiviles_attributes=(attributes)
@estadosCiviles ||= {}
@estadosCiviles =EstadosCivil.new(attributes)
end
def datosGenerales_attributes=(attributes)
@datosGenerales ||= {}
attributes[:perfilId] = @id
@datosGenerales =DatoGeneral.new(attributes)
end
def datosNacimiento_attributes=(attributes)
@datosNacimiento ||= {}
@datosNacimiento =DatoNacimiento.new(attributes)
end
def nacionalidades_attributes=(attributes)
@nacionalidades ||= {}
@nacionalidades =Nacionalidad.new(attributes)
end
def direcciones_attributes=(attributes)
@direcciones ||= {}
@direcciones =Direccion.new(attributes)
end
def identificaciones_attributes=(attributes)
@identificaciones ||= {}
@identificaciones =Identificacion.new(attributes)
end
def entidadesPrestadorasSalud_attributes=(attributes)
@entidadesPrestadorasSalud ||= {}
@entidadesPrestadorasSalud =EntidadPrestadoraSalud.new(attributes)
end
#fin -necesarios para nested form-
def self.find(id_perfil,access_token)
@@my_token = access_token
response = ApiConecction.get("/Perfiles/getUltimoPerfil",access_token,{idUsuario: id_perfil})
data_or_error = response.extract_data_or_message_error_from_response_api
@profile = Profile.new(data_or_error['perfil']) if response.successful?
@profile
end
def update(params = {}, access_token)
self.nombres = params[:nombres_attributes] if params[:nombres_attributes]
self.estadosCiviles = params[:estadosCiviles_attributes] if params[:estadosCiviles_attributes]
self.datosGenerales = params[:datosGenerales_attributes] if params[:datosGenerales_attributes]
self.datosNacimiento = params[:datosNacimiento_attributes] if params[:datosNacimiento_attributes]
self.nacionalidades = params[:nacionalidades_attributes] if params[:nacionalidades_attributes]
self.direcciones = params[:direcciones_attributes] if params[:direcciones_attributes]
self.identificaciones = params[:identificaciones_attributes] if params[:identificaciones_attributes]
self.entidadesPrestadorasSalud = params[:entidadesPrestadorasSalud_attributes] if params[:entidadesPrestadorasSalud_attributes]
carrier = self.changed
p self.changes
send_endpoint(self.changed,access_token)
changes_applied
return carrier
end
def send_endpoint(endpoints,access_token)
endpoints.each do |endpoint|
case endpoint
when 'nombres'
Nombre.new(nombres).create(access_token,@nombres_id_ant, id)
when 'estadosCiviles'
EstadoCivil.new(self.estadosCiviles).create(access_token, @estadosCiviles_id_ant, id)
when 'datosGenerales'
DatoGeneral.new(datosGenerales).create(access_token, @datosGenerales_id_ant, id)
when 'datosNacimiento'
DatoNacimiento.new(datosNacimiento).create(access_token, @datosNacimiento_id_ant, id)
when 'nacionalidades'
Nacionalidad.new(nacionalidades).create(access_token, @nacionalidades_id_ant, id)
when 'direcciones'
Direccion.new(direcciones).create(access_token, @direcciones_id_ant, id)
when 'identificaciones'
Identificacion.new(identificaciones).create(access_token, @identificaciones_id_ant, id)
when 'entidadesPrestadorasSalud'
EntidadPrestadoraSalud.new(entidadesPrestadorasSalud).create(access_token, @entidadesPrestadorasSalud_id_ant, id)
end
end
end
# para saber si el objeto no es nuevo , lo utiliza el form_for para elegir la ruta del sumbit
def persisted?
id.present?
end
end
class ProfilesController < ApplicationController
# before_action :set_profile, only: [:show, :edit, :update, :destroy]
def show
@profile = Profile.find(current_user.userId, current_user.id)
signos = Concepto.find_all(current_user.id)
observaciones = Observacion.find(current_user.userId, current_user.id)
@signos = ConceptoPresenter.new(signos, observaciones)
@signos.todos
render :edit unless @profile.nombres.primerNombre.present?
end
def edit
@profile ||= Profile.find(current_user.userId, current_user.id)
end
def update
@profile = Profile.find(current_user.userId, current_user.id)
@cambios = @profile.update(profiles_params, current_user.id)
if quick_params[:trigger]
respond_to do |format|
format.js
end
else
redirect_to @profile, notice: 'Actualización exitosa'
end
end
def calendar; end
def apps; end
def observaciones
@observacion = Observacion.new
response = @observacion.update(params, current_user.userId, current_user.id)
return unless response == true
@dato = params[:valor]
# se guarda para pasarlo a la respuesta js y actualizarlo en la vista
@origen = "#{params[:conceptoId]}-#{params[:campoId]}"
respond_to do |format|
format.js
end
end
def update_avatar
@avatar = Avatar.new
file = params[:file]
response = @avatar.update_avatar(file, current_user.id)
@new_url = "#{ENV['URL_API_NODE']}#{response}"
respond_to do |format|
format.js
end
end
def subir_anexo
p params
@anexo = Anexo.new
response_size = @anexo.testear_size(params, current_user.id)
check_size = JSON.parse(response_size.response_body)['archivoPermitido']
return unless check_size
response_name = @anexo.testear_name(params, current_user.id)
check_name = JSON.parse(response_name.response_body)['archivoPermitido']
return unless check_name
go_upload = @anexo.subir_file(params, current_user.id)
check_upload = JSON.parse(go_upload.response_body)['archivoPermitido']
return unless check_upload
_register_upload = @anexo.register_upload(params, current_user.id)
respond_to do |format|
format.js
end
end
private
def profiles_params
params.require(:profile).permit(:id,:avatar,:usuarioId,
nombres_attributes: [:primerNombre,:segundoNombre, :primerApellido, :segundoApellido, :perfilId],
estadosCiviles_attributes: [:estadoCivil,:perfilId],
datosGenerales_attributes: [:genero, :grupoSanguineo, :raza,:perfilId ],
datosNacimiento_attributes: [:fechaNacimiento, :pais, :departamento, :municipio, :perfilId],
nacionalidades_attributes: [:nacionalidad, :perfilId],
direcciones_attributes: [:direccion, :direccionAlternativa, :ubicacion, :latitud, :longitud, :perfilId],
identificaciones_attributes: [:numeroIdentificacion, :tipoIdentificacion, :lugarExpedicion, :perfilId],
entidadesPrestadorasSalud_attributes: [:eps, :centroSalud, :lugarAtencion, :codigoPrestadorServicio, :planComplementarioSalud, :perfilId]
)
end
def quick_params
params.permit(:trigger)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment