Make dev seeds independent on available locales

Some developers work on CONSUL installations where Spanish and/or
English aren't part of the available locales. In those cases, the
`dev_seed` task was crashing because we were using attributes like
`name_en` and `name_es`.

So we're using attributes for random locales instead.

We're using a proc so we don't have code like this all over the place:

random_locales.map do |locale|
  I18n.with_locale(locale) do
    phase.name = I18n.t("budgets.phase.#{phase.kind}")
    phase.save!
  end
end

This would make the code harder to read and would execute a `save!` once
per locale, which would make the task much slower.

We could also avoid the procs writing something like:

def random_locales_attributes(**attribute_names_with_values)
  random_locales.each_with_object({}) do |locale, attributes|
    I18n.with_locale(locale) do
      attribute_names_with_values.each do |attribute_name, (i18n_key, i18n_args)|
        value = I18n.t(i18n_key, (i18n_args || {}).merge(language: I18n.t("i18n.language.name")))
        attributes["#{attribute_name}_#{locale.to_s.underscore}"] = value
      end
    end
  end
end

And calling the method with with:

random_locales_attributes(name: ["seeds.budgets.name", year: Date.current.year - 1])

However, this code would also be different that what we usually do, we'd
have to apply some magic to pass the `language:` parameter, and the
strings wouldn't be recognized by i18n-tasks, so we aren't sure we're
really gaining anything.
This commit is contained in:
Javi Martín
2021-11-09 23:25:16 +01:00
parent e9d7d2744d
commit 490fe5fd11
7 changed files with 197 additions and 161 deletions

View File

@@ -1,5 +1,18 @@
en: en:
seeds: seeds:
admin_notifications:
budget:
title: "We are closing the Participatory Budget!!"
body: "Hurry up and create a last proposal before it ends next in few days!"
help:
title: "Help us translate consul"
body: "If you are proficient in a language, please help us translate consul!."
map:
title: "You can now geolocate proposals & investments"
body: "When you create a proposal or investment you now can specify a point on a map."
proposal:
title: "Do you have a proposal?"
body: "Remember you can create a proposal with your ideas and people will discuss & support it."
settings: settings:
official_level_1_name: Official position 1 official_level_1_name: Official position 1
official_level_2_name: Official position 2 official_level_2_name: Official position 2
@@ -14,6 +27,27 @@ en:
organizations: organizations:
human_rights: Human Rights human_rights: Human Rights
neighborhood_association: Neighborhood Association neighborhood_association: Neighborhood Association
cards:
budget:
title: "How do participatory budgets work?"
description: "Participatory budgets allow citizens to propose and decide directly how to spend part of the budget, with monitoring and rigorous evaluation of proposals by the institution. Maximum effectiveness and control with satisfaction for everyone."
link_text: "More about Participatory budgets"
label: "Participatory budgets"
debate:
title: "How do debates work?"
description: "Anyone can open threads on any subject, creating separate spaces where people can discuss the proposed topic. Debates are valued by everybody, to highlight the most important issues."
link_text: "More about debates"
label: "Debates"
header:
title: "CONSUL"
description: "Free software for citizen participation."
link_text: "More information"
label: "Welcome to"
proposal:
title: "How do citizen proposals work?"
description: "A space for everyone to create a citizen's proposal and seek supports. Proposals which reach to enough supports will be voted and so, together we can decide the issues that matter to us."
link_text: "More about proposals"
label: "Citizen proposals"
categories: categories:
associations: Associations associations: Associations
culture: Culture culture: Culture
@@ -36,6 +70,9 @@ en:
groups: groups:
all_city: All City all_city: All City
districts: Districts districts: Districts
phases:
description: "Description in %{language}"
summary: "Summary in %{language}"
valuator_groups: valuator_groups:
culture_and_sports: Culture & Sports culture_and_sports: Culture & Sports
gender_and_diversity: Gender & Diversity Policies gender_and_diversity: Gender & Diversity Policies
@@ -46,6 +83,10 @@ en:
bidding: Bidding bidding: Bidding
executing_project: Executing the project executing_project: Executing the project
executed: Executed executed: Executed
legislation:
draft_versions:
title: "Version %{number}"
body: "Draft version in %{language}"
polls: polls:
current_poll: "Current Poll" current_poll: "Current Poll"
current_poll_geozone_restricted: "Current Poll Geozone Restricted" current_poll_geozone_restricted: "Current Poll Geozone Restricted"

View File

@@ -1,5 +1,18 @@
es: es:
seeds: seeds:
admin_notifications:
budget:
title: "Últimos días para crear proyectos de Presupuestos Participativos"
body: "Quedan pocos dias para que se cierre el plazo de presentación de proyectos de inversión para los presupuestos participativos!"
help:
title: "Ayúdanos a traducir CONSUL"
body: "Si dominas un idioma, ayúdanos a completar su traducción en CONSUL."
map:
title: "Ahora puedes geolocalizar propuestas y proyectos de inversión"
body: "Cuando crees una propuesta o proyecto de inversión podrás especificar su localización en el mapa"
proposal:
title: "Tienes una propuesta?"
body: "Recuerda que puedes crear propuestas y los ciudadanos las debatirán y apoyarán."
settings: settings:
official_level_1_name: Cargo oficial 1 official_level_1_name: Cargo oficial 1
official_level_2_name: Cargo oficial 2 official_level_2_name: Cargo oficial 2
@@ -14,6 +27,27 @@ es:
organizations: organizations:
human_rights: Derechos Humanos human_rights: Derechos Humanos
neighborhood_association: Asociación Vecinal neighborhood_association: Asociación Vecinal
cards:
budget:
title: "¿Cómo funcionan los propuestos participativos?"
description: "Los presupuestos participativos permiten que los ciudadanos propongan y decidan directamente cómo gastar parte del presupuesto, con la supervisión y valoración de la institución. Máxima eficacia y control para la satisfacción de todos"
link_text: "Más sobre presupuestos participativos"
label: "Presupuestos participativos"
debate:
title: "¿Cómo funcionan los debates?"
description: "Cualquiera puede iniciar un debate sobre cualquier tema, creando un espacio separado donde compartir puntos de vista con otras personas. Los debates son valorados por todos para destacar los temas más importantes."
link_text: "Más sobre debates"
label: "Debates"
header:
title: "CONSUL"
description: "Software libre para la participación ciudadana."
link_text: "Más información"
label: "Bienvenido a"
proposal:
title: "¿Cómo funcionan las propuestas ciudadanas?"
description: "Un espacio para que el ciudadano cree una propuesta y busque apoyo. Las propuestas que obtengan el apoyo necesario serán votadas. Así juntos podemos decidir sobre los temas que nos importan."
link_text: "Más sobre propuestas"
label: "Propuestas ciudadanas"
categories: categories:
associations: Asociaciones associations: Asociaciones
culture: Cultura culture: Cultura
@@ -36,6 +70,9 @@ es:
groups: groups:
all_city: Toda la Ciudad all_city: Toda la Ciudad
districts: Distritos districts: Distritos
phases:
description: "Descripción en %{language}"
summary: "Resumen en %{language}"
valuator_groups: valuator_groups:
culture_and_sports: Cultura y Deportes culture_and_sports: Cultura y Deportes
gender_and_diversity: Políticas de Género y Diversidad gender_and_diversity: Políticas de Género y Diversidad
@@ -46,6 +83,10 @@ es:
bidding: Licitación bidding: Licitación
executing_project: Ejecutando el proyecto executing_project: Ejecutando el proyecto
executed: Ejecutado executed: Ejecutado
legislation:
draft_versions:
title: "Versión %{number}"
body: "Borrador en %{language}"
polls: polls:
current_poll: "Votación Abierta" current_poll: "Votación Abierta"
current_poll_geozone_restricted: "Votación Abierta restringida por geozona" current_poll_geozone_restricted: "Votación Abierta restringida por geozona"

View File

@@ -21,6 +21,16 @@ def random_locales
[I18n.default_locale, *(I18n.available_locales & %i[en es]), *I18n.available_locales.sample(4)].uniq.take(5) [I18n.default_locale, *(I18n.available_locales & %i[en es]), *I18n.available_locales.sample(4)].uniq.take(5)
end end
def random_locales_attributes(**attribute_names_with_values)
random_locales.each_with_object({}) do |locale, attributes|
I18n.with_locale(locale) do
attribute_names_with_values.each do |attribute_name, value_proc|
attributes["#{attribute_name}_#{locale.to_s.underscore}"] = value_proc.call
end
end
end
end
require_relative "dev_seeds/settings" require_relative "dev_seeds/settings"
require_relative "dev_seeds/geozones" require_relative "dev_seeds/geozones"
require_relative "dev_seeds/users" require_relative "dev_seeds/users"

View File

@@ -1,47 +1,33 @@
section "Creating Admin Notifications & Templates" do section "Creating Admin Notifications & Templates" do
AdminNotification.create!( AdminNotification.create!(
title_en: "Do you have a proposal?", random_locales_attributes(
title_es: "Tienes una propuesta?", %i[title body].map do |attribute|
[attribute, -> { I18n.t("seeds.admin_notifications.proposal.#{attribute}") }]
body_en: "Remember you can create a proposal with your ideas and "\ end.to_h
"people will discuss & support it.", ).merge(link: "#{Setting["url"]}/proposals", segment_recipient: "administrators")
body_es: "Recuerda que puedes crear propuestas y los ciudadanos las debatirán y apoyarán.",
link: "#{Setting["url"]}/proposals",
segment_recipient: "administrators"
).deliver ).deliver
AdminNotification.create!( AdminNotification.create!(
title_en: "Help us translate consul", random_locales_attributes(
title_es: "Ayúdanos a traducir CONSUL", %i[title body].map do |attribute|
[attribute, -> { I18n.t("seeds.admin_notifications.help.#{attribute}") }]
body_en: "If you are proficient in a language, please help us translate consul!.", end.to_h
body_es: "Si dominas un idioma, ayúdanos a completar su traducción en CONSUL.", ).merge(link: "https://crwd.in/consul", segment_recipient: "administrators")
link: "https://crwd.in/consul",
segment_recipient: "administrators"
).deliver ).deliver
AdminNotification.create!( AdminNotification.create!(
title_en: "You can now geolocate proposals & investments", random_locales_attributes(
title_es: "Ahora puedes geolocalizar propuestas y proyectos de inversión", %i[title body].map do |attribute|
[attribute, -> { I18n.t("seeds.admin_notifications.map.#{attribute}") }]
body_en: "When you create a proposal or investment you now can specify a point on a map", end.to_h
body_es: "Cuando crees una propuesta o proyecto de inversión podrás especificar "\ ).merge(segment_recipient: "administrators")
"su localización en el mapa",
segment_recipient: "administrators"
).deliver ).deliver
AdminNotification.create!( AdminNotification.create!(
title_en: "We are closing the Participatory Budget!!", random_locales_attributes(
title_es: "Últimos días para crear proyectos de Presupuestos Participativos", %i[title body].map do |attribute|
[attribute, -> { I18n.t("seeds.admin_notifications.budget.#{attribute}") }]
body_en: "Hurry up and create a last proposal before it ends next in few days!", end.to_h
body_es: "Quedan pocos dias para que se cierre el plazo de presentación de proyectos de "\ ).merge(segment_recipient: "administrators", sent_at: nil)
"inversión para los presupuestos participativos!",
segment_recipient: "administrators",
sent_at: nil
) )
end end

View File

@@ -28,75 +28,68 @@ end
section "Creating Budgets" do section "Creating Budgets" do
Budget.create!( Budget.create!(
name_en: "#{I18n.t("seeds.budgets.budget", locale: :en)} #{Date.current.year - 1}", {
name_es: "#{I18n.t("seeds.budgets.budget", locale: :es)} #{Date.current.year - 1}",
currency_symbol: I18n.t("seeds.budgets.currency"), currency_symbol: I18n.t("seeds.budgets.currency"),
phase: "finished", phase: "finished",
published: true published: true
}.merge(
random_locales_attributes(name: -> { "#{I18n.t("seeds.budgets.budget")} #{Date.current.year - 1}" })
)
) )
Budget.create!( Budget.create!(
name_en: "#{I18n.t("seeds.budgets.budget", locale: :en)} #{Date.current.year}", {
name_es: "#{I18n.t("seeds.budgets.budget", locale: :es)} #{Date.current.year}",
currency_symbol: I18n.t("seeds.budgets.currency"), currency_symbol: I18n.t("seeds.budgets.currency"),
phase: "accepting", phase: "accepting",
published: true published: true
}.merge(
random_locales_attributes(name: -> { "#{I18n.t("seeds.budgets.budget")} #{Date.current.year}" })
)
) )
Budget.find_each do |budget| Budget.find_each do |budget|
budget.phases.each do |phase| budget.phases.each do |phase|
random_locales.map do |locale| phase.update!(random_locales_attributes(
Globalize.with_locale(locale) do name: -> { I18n.t("budgets.phase.#{phase.kind}") },
phase.name = I18n.t("budgets.phase.#{phase.kind}") summary: -> { I18n.t("seeds.budgets.phases.summary", language: I18n.t("i18n.language.name")) },
phase.description = "Description for locale #{locale}" description: -> { I18n.t("seeds.budgets.phases.description", language: I18n.t("i18n.language.name")) }
phase.summary = "Summary for locale #{locale}" ))
phase.save!
end
end
end end
end end
Budget.all.each do |budget| Budget.all.each do |budget|
city_group = budget.groups.create!( city_group = budget.groups.create!(
name_en: I18n.t("seeds.budgets.groups.all_city", locale: :en), random_locales_attributes(name: -> { I18n.t("seeds.budgets.groups.all_city") })
name_es: I18n.t("seeds.budgets.groups.all_city", locale: :es)
) )
city_group.headings.create!( city_group.headings.create!(
name_en: I18n.t("seeds.budgets.groups.all_city", locale: :en), {
name_es: I18n.t("seeds.budgets.groups.all_city", locale: :es),
price: 1000000, price: 1000000,
population: 1000000, population: 1000000,
latitude: "40.416775", latitude: "40.416775",
longitude: "-3.703790" longitude: "-3.703790"
}.merge(
random_locales_attributes(name: -> { I18n.t("seeds.budgets.groups.all_city") })
)
) )
districts_group = budget.groups.create!( districts_group = budget.groups.create!(
name_en: I18n.t("seeds.budgets.groups.districts", locale: :en), random_locales_attributes(name: -> { I18n.t("seeds.budgets.groups.districts") })
name_es: I18n.t("seeds.budgets.groups.districts", locale: :es)
) )
[ [
{ random_locales_attributes(name: -> { I18n.t("seeds.geozones.north_district") }).merge(
name_en: I18n.t("seeds.geozones.north_district", locale: :en),
name_es: I18n.t("seeds.geozones.north_district", locale: :es),
population: 350000 population: 350000
}, ),
{ random_locales_attributes(name: -> { I18n.t("seeds.geozones.west_district") }).merge(
name_en: I18n.t("seeds.geozones.west_district", locale: :en), population: 300000
name_es: I18n.t("seeds.geozones.west_district", locale: :es), ),
population: 300000, random_locales_attributes(name: -> { I18n.t("seeds.geozones.east_district") }).merge(
}, population: 200000
{ ),
name_en: I18n.t("seeds.geozones.east_district", locale: :en), random_locales_attributes(name: -> { I18n.t("seeds.geozones.central_district") }).merge(
name_es: I18n.t("seeds.geozones.east_district", locale: :es), population: 150000
population: 200000, )
},
{
name_en: I18n.t("seeds.geozones.central_district", locale: :en),
name_es: I18n.t("seeds.geozones.central_district", locale: :es),
population: 150000,
}
].each do |heading_params| ].each do |heading_params|
districts_group.headings.create!(heading_params.merge( districts_group.headings.create!(heading_params.merge(
price: rand(5..10) * 100000, price: rand(5..10) * 100000,

View File

@@ -25,12 +25,15 @@ section "Creating collaborative legislation" do
Legislation::Process.find_each do |process| Legislation::Process.find_each do |process|
(1..3).each do |i| (1..3).each do |i|
process.draft_versions.create!(title_en: "Version #{i}", process.draft_versions.create!(random_locales_attributes(
title_es: "Versión #{i}", title: -> { I18n.t("seeds.legislation.draft_versions.title", number: i) },
body_en: ["Draft version in English", body: -> do
*Faker::Lorem.paragraphs].join("\n\n"), [
body_es: ["Versión borrador en Español", I18n.t("seeds.legislation.draft_versions.body", language: I18n.t("i18n.language.name")),
*Faker::Lorem.paragraphs].join("\n\n")) *Faker::Lorem.paragraphs
].join("\n\n")
end
))
end end
end end
end end

View File

@@ -8,88 +8,50 @@ section "Creating header and cards for the homepage" do
end end
Widget::Card.create!( Widget::Card.create!(
title_en: "CONSUL", random_locales_attributes(
title_es: "CONSUL", %i[title description link_text label].map do |attribute|
[attribute, -> { I18n.t("seeds.cards.header.#{attribute}") }]
description_en: "Free software for citizen participation.", end.to_h
description_es: "Software libre para la participación ciudadana.", ).merge(
link_text_en: "More information",
link_text_es: "Más información",
label_en: "Welcome to",
label_es: "Bienvenido a",
link_url: "http://consulproject.org/", link_url: "http://consulproject.org/",
header: true, header: true,
image_attributes: create_image_attachment("header") image_attributes: create_image_attachment("header")
) )
)
Widget::Card.create!( Widget::Card.create!(
title_en: "How do debates work?", random_locales_attributes(
title_es: "¿Cómo funcionan los debates?", %i[title description link_text label].map do |attribute|
[attribute, -> { I18n.t("seeds.cards.debate.#{attribute}") }]
description_en: "Anyone can open threads on any subject, creating separate spaces "\ end.to_h
"where people can discuss the proposed topic. Debates are valued by "\ ).merge(
"everybody, to highlight the most important issues.",
description_es: "Cualquiera puede iniciar un debate sobre cualquier tema, creando un espacio "\
"separado donde compartir puntos de vista con otras personas. Los debates son "\
"valorados por todos para destacar los temas más importantes.",
link_text_en: "More about debates",
link_text_es: "Más sobre debates",
label_en: "Debates",
label_es: "Debates",
link_url: "https://youtu.be/zU_0UN4VajY", link_url: "https://youtu.be/zU_0UN4VajY",
header: false, header: false,
image_attributes: create_image_attachment("debate") image_attributes: create_image_attachment("debate")
) )
)
Widget::Card.create!( Widget::Card.create!(
title_en: "How do citizen proposals work?", random_locales_attributes(
title_es: "¿Cómo funcionan las propuestas ciudadanas?", %i[title description link_text label].map do |attribute|
[attribute, -> { I18n.t("seeds.cards.proposal.#{attribute}") }]
description_en: "A space for everyone to create a citizen's proposal and seek supports. "\ end.to_h
"Proposals which reach to enough supports will be voted and so, together we "\ ).merge(
"can decide the issues that matter to us.",
description_es: "Un espacio para que el ciudadano cree una propuesta y busque apoyo. "\
"Las propuestas que obtengan el apoyo necesario serán votadas. Así juntos "\
"podemos decidir sobre los temas que nos importan.",
link_text_en: "More about proposals",
link_text_es: "Más sobre propuestas",
label_en: "Citizen proposals",
label_es: "Propuestas ciudadanas",
link_url: "https://youtu.be/ZHqBpT4uCoM", link_url: "https://youtu.be/ZHqBpT4uCoM",
header: false, header: false,
image_attributes: create_image_attachment("proposal") image_attributes: create_image_attachment("proposal")
) )
)
Widget::Card.create!( Widget::Card.create!(
title_en: "How do participatory budgets work?", random_locales_attributes(
title_es: "¿Cómo funcionan los propuestos participativos?", %i[title description link_text label].map do |attribute|
[attribute, -> { I18n.t("seeds.cards.budget.#{attribute}") }]
description_en: "Participatory budgets allow citizens to propose and decide directly "\ end.to_h
"how to spend part of the budget, with monitoring and rigorous evaluation "\ ).merge(
"of proposals by the institution. Maximum effectiveness and control with "\
"satisfaction for everyone.",
description_es: "Los presupuestos participativos permiten que los ciudadanos propongan y "\
"decidan directamente cómo gastar parte del presupuesto, con la supervisión "\
"y valoración de la institución. Máxima eficacia y control para la "\
"satisfacción de todos",
link_text_en: "More about Participatory budgets",
link_text_es: "Más sobre presupuestos participativos",
label_en: "Participatory budgets",
label_es: "Presupuestos participativos",
link_url: "https://youtu.be/igQ8KGZdk9c", link_url: "https://youtu.be/igQ8KGZdk9c",
header: false, header: false,
image_attributes: create_image_attachment("budget") image_attributes: create_image_attachment("budget")
) )
)
end end