Sviluppare plugin per Discourse - Parte 3 - Aggiungere impostazioni personalizzate del sito

Precedente tutorial: Developing Discourse Plugins - Part 2 - Connect to a plugin outlet


Impostazioni Sito

Se visiti /admin/site_settings su un Discourse su cui hai capacità di amministratore, vedrai un elenco di impostazioni di configurazione. Appena installato, forniamo quelle che riteniamo siano le impostazioni migliori per un’installazione di Discourse, ma comprendiamo anche che le persone vogliono modificare le loro installazioni per rendere il loro forum esattamente come desiderano.

È probabile che, a meno che il tuo plugin non sia molto semplice, tu voglia aggiungere impostazioni che gli utenti del tuo plugin possano modificare e utilizzare per configurare le funzionalità. Fortunatamente, questo è piuttosto facile da fare!

config/settings.yml

La prima cosa che dovrai fare è creare config/settings.yml all’interno della cartella del tuo plugin. Questo file delineerà tutte le impostazioni di cui il tuo plugin avrà bisogno. Ecco un file di esempio:

plugins:
  awesomeness_enabled:
    default: true
    client: true
  awesomeness_max_volume:
    default: 10
    client: true

Il file deve essere in formato YAML. YAML può essere piuttosto esigente, quindi se Discourse ha problemi a caricare le tue impostazioni, ti suggerisco di provare a convalidare il tuo YAML con uno strumento come YAMLint.

Spiegherò il file di esempio in dettaglio. Il livello superiore è plugins e questo dice a Discourse che vogliamo che queste impostazioni appaiano sotto “Plugins” nelle impostazioni del sito.

Successivamente, vengono dichiarate due impostazioni, awesomeness_enabled e awesomeness_max_volume. Discourse deduce il tipo delle impostazioni dal valore predefinito, quindi awesomeness_enabled è un booleano e awesomeness_max_volume è un numero.

Il client: true è importante da capire. Discourse è composto da due applicazioni principali, l’API lato server scritta in Ruby on Rails e l’applicazione lato client scritta in Ember.js. Per impostazione predefinita, non esponiamo le impostazioni all’app client Ember.js a meno che tu non aggiunga client: true. Lo facciamo perché alcune impostazioni sono private come le chiavi API e non dovrebbero essere inviate agli utenti finali. Inoltre, se inviassimo ogni impostazione al client, potrebbe essere un carico notevole per gli utenti finali scaricarle!

Nel nostro esempio, vogliamo che entrambe queste impostazioni siano accessibili nel mondo JavaScript così come nel mondo lato server.

Un secondo passo importante

Prima di poter utilizzare le impostazioni del sito appena aggiunte, devi aggiungere le traduzioni per esse. Poiché Discourse supporta molte lingue, qualsiasi testo che aggiungi dovrà supportare la traduzione in altre lingue.

Creiamo le traduzioni per le nostre impostazioni in inglese:

config/locales/server.en.yml

en:
  site_settings:
    awesomeness_enabled: "Is this plugin awesome?"
    awesomeness_max_volume: "What is the maximum volume possible?"

Le etichette che abbiamo aggiunto in quel file verranno visualizzate nella sezione admin. È buona norma essere il più chiari possibile su ciò che l’impostazione realizza.

Dichiarare l’impostazione come ‘impostazione di abilitazione’

Ora che abbiamo la nostra impostazione del sito, dovremmo dire a Discourse che è quella che attiva e disattiva le nostre funzionalità.

Apri il tuo file plugin.rb e aggiungi la seguente riga sotto i commenti dei metadati:

enabled_site_setting :awesomeness_enabled

Assicurati di iniziare tutte le altre impostazioni con “awesomeness_” affinché il pulsante delle impostazioni in /admin/plugins funzioni correttamente.

Accesso alle tue nuove impostazioni

Innanzitutto, dovrai riavviare il tuo server di sviluppo affinché le impostazioni abbiano effetto. Una volta fatto ciò, le impostazioni dovrebbero essere disponibili per il tuo codice lato server e client.

Iniettiamo automaticamente le impostazioni del sito nella maggior parte degli oggetti JavaScript, quindi se stai dichiarando un Component, Controller, Route, View o Model dovresti essere in grado di accedere all’impostazione del sito semplicemente usando this.siteSettings.awesomeness_enabled. Nella maggior parte dei template handlebars dovresti anche essere in grado di dire {{siteSettings.awesomeness_enabled}} e il valore dell’impostazione verrà visualizzato.

Non abbiamo ancora trattato molto materiale Ruby in questa serie, ma se vuoi accedere alle impostazioni del sito nell’applicazione Ruby puoi farlo tramite: SiteSetting.awesomeness_enabled

Ora vai avanti e aggiungi impostazioni personalizzate ai tuoi plugin!


Altro nella serie

Parte 1: Plugin Basics
Parte 2: Plugin Outlets
Parte 3: Questo argomento
Parte 4: git setup
Parte 5: Admin interfaces
Parte 6: Acceptance tests
Parte 7: Publish your plugin


Questo documento è controllato tramite versione - suggerisci modifiche su github.

34 Mi Piace

For those more familiar with YAML, this was probably obvious, and thanks to YAMLint that you referenced I was able to figure this out pretty quick, but I thought it was worth mentioning that the format for the config/locales/server.en.yml needs to specifically be:

en:
  site_settings:
    awesomeness_enabled: "Is this plugin awesome?"
    max_volume: "What is the maximum volume possible?"

Correct?

Another quick question, it’s great that I can get to the settings by clicking on the Change Settings button, but how do I get the plugin specific Settings button directly to the right of the plugin like the poll plugin?

https://s3.amazonaws.com/f.cl.ly/items/162n220f0M0P3e0j2U3M/Image%202015-07-29%20at%207.29.28%20PM.png

Or is that a little too much for a Beginner’s Guide?

4 Mi Piace

I updated the guide to fix both of those :smile:

4 Mi Piace

How do you get the settings button to pre-populate the search field like Discourse Tagging does? I feel like I’m missing something obvious.

Edit: Nevermind, I figured it out. You had to use *_enabled to get it to filter. I originally didn’t have an enabled setting because the URL was simply the factor for determining if it is enabled.

1 Mi Piace

For some reason, {{siteSettings}} in the poster-name-right outlet returns undefined. I tested with other outlets and the return the expected value. I’m not sure why :sadpanda:

Had to work around it by using {{Discourse.SiteSettings}}

1 Mi Piace

This isn’t working because the Post view code path is some of the oldest code we have and it doesn’t do all the automatic stuff newer code can do :frowning:

I’ve come up with a fix that I think will solve your problem:

In the future I’ll be able to remove this hack and it’ll just work.

3 Mi Piace

Hey @eviltrout how can I add a user setting? I mean a setting for a plugin that every user can change on his profile? Can I set a default too?

I guess is the same as an Custom User Field, so can I create a new User Field from a plugin?

Unfortunately there’s no easy way to do this right now. There is probably a good argument to be made for such an API for plugin authors.

Until then the way to do it is to add the fields via plugin outlets to the user preferences, tap into serializers and saving logic to store the setting the PluginStore.

1 Mi Piace

I ran into this a while back too. We have to expose the field in the site settings too. I’ll see if I can add a PR to make this easier.

1 Mi Piace

For anyone following this tutorial and trying to get SiteSettings.awesomeness_enabled to return anything in a rails console, be aware that the tutorial is wrong. It should be SiteSetting.awesomeness_enabled (Setting without the s at the end!)

1 Mi Piace

Hmmm, this works for me in the hbs files

{{#if siteSettings.plugin_outlet_locations_enabled}}

Different syntax depending on where it’s being called from?

EDIT
Ah, the singular - plural Rails “magic” thing.

Nope, your first guess was correct >.>

JS has Discourse.SiteSettings but Rails has SiteSetting.

3 Mi Piace

Oops! Thanks for letting me know. I’ve updated the tutorial.

2 Mi Piace

Well, I believe some infrastructure are not complete yet. But I am refurnishing old login plugins while it’s worthwhile to asking the future change to plugin infra. Shall I move settings from login to plugin prefix?

I would recommend to do that, yes.

1 Mi Piace

Just to clarify, this is only the case if you say client: true, right?

Yes, that is correct. Javascript gets access to the “client side” site settings.

2 Mi Piace

I do not completely understand this statement. I set it to client: false but it was still visible in admin settings. What exactly happens if you set client to false.

Thank you.

We ship up a big JSON object of all the site settings that have client: true to all users, so those are considered public and viewable.

If they don’t have client: true then they are meant to be available from the server side. The admin section is an exception - we need to return all site settings to admin users so they can be changed! It uses a different API to get them all.

9 Mi Piace

Work for me! 2018-4-28

Code

config/settings.yml

config/locales/server.en.yml

plugin.rb

Result

http://localhost:3000/admin/site_settings/category/plugins


(oh, I saw the translation missing hint)

Thanks!

3 Mi Piace