5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-07-03 23:55:46 +00:00

asegurarse que guardamos todo como objectos naturales de ruby

This commit is contained in:
f 2018-07-24 17:49:32 -03:00
parent 02733728a3
commit 586f4c5824
No known key found for this signature in database
GPG key ID: F3FDAB97B5F9F7E7
2 changed files with 24 additions and 8 deletions

View file

@ -54,8 +54,7 @@ class PostsController < ApplicationController
@site = find_site
@lang = find_lang(@site)
@post = find_post(@site)
@post.update_attributes(post_params)
@post.update_attributes(repair_nested_params(post_params))
if @post.save
redirect_to site_posts_path(@site, category: session[:category], lang: @lang)
@ -70,4 +69,19 @@ class PostsController < ApplicationController
def post_params
params.require(:post).permit(@post.template_params)
end
# https://gist.github.com/bloudermilk/2884947#gistcomment-1915521
def repair_nested_params(obj)
obj.each do |key, value|
if value.is_a?(ActionController::Parameters) || value.is_a?(Hash)
# If any non-integer keys
if value.keys.find {|k, _| k =~ /\D/ }
repair_nested_params(value)
else
obj[key] = value.values
value.values.each {|h| repair_nested_params(h) }
end
end
end
end
end

View file

@ -196,12 +196,10 @@ class Post
# imita Model.update_attributes de ActiveRecord
def update_attributes(attrs)
# el cuerpo se maneja por separado
@content = attrs.delete('content') if attrs.key? 'content'
# convertir los hashes en arrays si los campos son anidados
# usamos to_h por todos lados porque sino son
# usamos to_hash por todos lados porque sino son
# HashWithIndifferentAccess
attrs = attrs.to_h.map do |k,v|
_attrs = attrs.to_hash.map do |k,v|
t = template_fields.find { |t| t.key == k }
if t
# Subir la imagen!
@ -224,14 +222,17 @@ class Post
end
if t.nested?
v = t.array? ? v.values.map(&:to_h) : v.to_h
v = t.array? ? v.map(&:to_hash) : v.to_hash
end
end
{ k => v }
end.reduce(Hash.new, :merge).stringify_keys
merge_with_front_matter! attrs
# el cuerpo se maneja por separado
@content = _attrs.delete('content') if _attrs.key? 'content'
merge_with_front_matter! _attrs
end
# Requisitos para que el post sea válido
@ -306,6 +307,7 @@ class Post
end
end
# TODO convertir a hash para que sea más fácil buscar uno
def template_fields
return [] unless template
@template_fields ||= template.front_matter.map do |key, contents|