From 57b652bbb1a77d9fdf20555f6485fd2037044ca3 Mon Sep 17 00:00:00 2001 From: f Date: Thu, 13 Feb 2020 12:38:53 -0300 Subject: [PATCH] usar structs para validar datos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit los structs son como hashes con llaves fijas. si llamamos a una que no existe vamos a tener una excepción --- app/models/site.rb | 20 +++++++++++++++----- app/models/site/static_file_migration.rb | 2 +- app/views/posts/index.haml | 2 +- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/app/models/site.rb b/app/models/site.rb index d84a7cc..ffdb447 100644 --- a/app/models/site.rb +++ b/app/models/site.rb @@ -169,10 +169,16 @@ class Site < ApplicationRecord # @param lang: [String|Symbol] traer los artículos de este idioma def posts(lang: nil) read - @posts ||= {} - lang ||= I18n.locale - return @posts[lang] if @posts.key? lang + # Traemos los posts del idioma actual por defecto + lang ||= I18n.locale + + # Crea un Struct dinámico con los valores de los locales, si + # llegamos a pasar un idioma que no existe vamos a tener una + # excepción NoMethodError + @posts ||= Struct.new(*locales.map(&:to_sym)).new + + return @posts[lang] unless @posts[lang].blank? @posts[lang] = PostRelation.new site: self @@ -201,11 +207,15 @@ class Site < ApplicationRecord # # @return { post: Layout } def layouts - @layouts ||= data.fetch('layouts', {}).map do |name, metadata| + # Crea un Struct dinámico cuyas llaves son los nombres de todos los + # layouts. Si pasamos un layout que no existe, obtenemos un + # NoMethodError + @layouts_struct ||= Struct.new(*data.fetch('layouts', {}).keys.map(&:to_sym), keyword_init: true) + @layouts ||= @layouts_struct.new(**data.fetch('layouts', {}).map do |name, metadata| { name.to_sym => Layout.new(site: self, name: name.to_sym, metadata: metadata.with_indifferent_access) } - end.inject(:merge) + end.inject(:merge)) end # Trae todos los valores disponibles para un campo diff --git a/app/models/site/static_file_migration.rb b/app/models/site/static_file_migration.rb index 48b3cf2..e787527 100644 --- a/app/models/site/static_file_migration.rb +++ b/app/models/site/static_file_migration.rb @@ -105,7 +105,7 @@ class Site # Encuentra todos los layouts con campos estáticos def layouts - @layouts ||= site.layouts.reject do |_, layout| + @layouts ||= site.layouts.to_h.reject do |_, layout| layout.metadata.select do |_, desc| STATIC_TYPES.include? desc['type'] end.empty? diff --git a/app/views/posts/index.haml b/app/views/posts/index.haml index 7e0ce3a..cded824 100644 --- a/app/views/posts/index.haml +++ b/app/views/posts/index.haml @@ -13,7 +13,7 @@ %h3= t('posts.new') %ul - - @site.layouts.keys.each do |layout| + - @site.layouts.to_h.keys.each do |layout| %li= link_to layout.to_s.humanize, new_site_post_path(@site, layout: layout)