Plugin Development: Beyond the Basics?

If you haven’t found the Ember docs yet, they’re probably the best place to start if the question is ‘WTF are you, Ember?’

A rough outline of how you could tackle this plugin:

  • Write a serializer which will output the data you need, given a file:
class FileSerializer < ActiveModel::Serializer
  attributes :filename, :href
end
  • Write a rails controller method which use that serializer to return the files in a json format:
class Globber::FilesController < ApplicationController
  def index
    @files = Dir.glob("files/**.*.rb")
    render json: ActiveModel::ArraySerializer.new(@files, each_serializer: FileSerializer)
  end
end
  • Expose an endpoint so that Ember can access the controller method:
Discourse::Application.routes.append do
  get '/globber/files' => 'globber/files#index'
end
  • On the ember side, make an ajax call which hits that endpoint and returns the json data you’re looking for:
import { ajax } from 'discourse/lib/ajax'
ajax('/globber/files').then((data) => { this.set('files', data) })
# ^^ 'files' is now a property that's accessible in the view
  • Then, in the ember template of the javascript controller, you can iterate through the files and display them seasoned to taste:
{{#each file as |files|}}
  <a href={{file.href}}>{{file.name}}</a>
{{/each}}

(NB: all code in this post is untested and subject to crappiness)

The only way I ever learned anything about writing plugins for Discourse was reading other people’s code (well, and asking questions on here ;)), so likely that’s the best way to go if you’re looking to expand your knowledge further.

11 לייקים