يخصص الصفحة الرئيسية لعرض المواضيع بناءً على اهتمامات المستخدم

أرغب في سماع رأيك في هذا المكون الإضافي. أنا أعمل على مكون إضافي سيسمح للزوار باختيار موضوع جديد لعرضه على الصفحة الرئيسية اعتمادًا على اهتماماتهم. لقد قمت بتدوين الفكرة ورسمت هذه الخطوة، لكنني لم أتعامل معها بعد.

plugin.rb

# plugins/custom_homepage/plugin.rb
# frozen_string_literal: true

# name: custom-homepage
# about: Customizes the homepage to show topics based on user interests
# version: 0.1
# authors: MHAT
# url: https://domain.com

enabled_site_setting :custom_homepage_enabled

after_initialize do
  # code to be executed after initialization
end
// plugins/custom_homepage/assets/javascripts/discourse/initializers/custom-homepage.js.es6

import { withPluginApi } from 'discourse/lib/plugin-api';

export default {
  name: 'custom-homepage',
  initialize(container) {
    withPluginApi('0.8', api => {
      api.modifyClass('component:topic-list', {
        didInsertElement() {
          this._super(...arguments);

          if (this.currentUser) {
            this.loadUserInterests();
          }
        },

        loadUserInterests() {
          const userId = this.currentUser.id;

          fetch(`/u/${userId}/preferences/interests`)
            .then(response => response.json())
            .then(data => {
              this.set('topics', this.sortTopicsByInterests(this.topics, data.interests));
            });
        },

        sortTopicsByInterests(topics, interests) {
          return topics.sort((a, b) => {
            const aScore = interests.includes(a.category_id) ? 1 : 0;
            const bScore = interests.includes(b.category_id) ? 1 : 0;

            return bScore - aScore;
          });
        }
      });
    });
  }
};
# plugins/custom_homepage/config/locales/server.en.yml
en:
  site_settings:
    custom_homepage_enabled: "Enable Custom Homepage"

  user:
    preferences:
      interests: "Interests"

# plugins/custom_homepage/config/discourse_plugin.yml
enabled_site_setting: custom_homepage_enabled

HTML للإعدادات

<script type="text/x-handlebars" data-template-name="/connectors/user-preferences/interests">
  <div class="control-group">
    <label class="control-label">{{i18n 'user.preferences.interests'}}</label>
    <div class="controls">
      {{input value=currentUser.custom_fields.interests class="form-control"}}
    </div>
  </div>
</script>
# plugins/custom_homepage/plugin.rb

after_initialize do
  User.register_custom_field_type('interests', :string)
  
  add_to_serializer(:current_user, :interests) do
    object.custom_fields['interests']
  end
end

شكراً لملاحظاتك واقتراحاتك للتحسين.

أنا تايلاندي. قد لا تبدو مهاراتي في اللغة الإنجليزية جيدة بشكل خاص. لقد حاولت تعلمها أثناء تطوير discourse.

أين يتم تطبيق /preferences/interests؟

أعتقد أنه من أجل التعامل مع اهتمامات المستخدم ودمجها في تفضيلات المستخدم، يجب إنشاء المسارات والإجراءات المتحكمة والقوالب المطلوبة.

ومع ذلك، هذا مجرد وجهة نظري، وهي مصممة ببساطة. لم أبدأ في بنائها بعد. قد لا تسير الأمور كما هو مخطط لها إذا حاولت.

إضافة مسار لتفضيلات المستخدم:
- أضف مسارًا سيتعامل مع الطلبات إلى /u/:username/preferences/interests.

```ruby
# plugins/custom_homepage/config/routes.rb
Discourse::Application.routes.append do
  get '/u/:username/preferences/interests' => 'custom_homepage#interests', constraints: { username: /[^\\/]+/ }
end
```

إنشاء إجراء المتحكم:
- حدد متحكمًا للتعامل مع الطلب وجلب اهتمامات المستخدم.

```ruby
# plugins/custom_homepage/app/controllers/custom_homepage_controller.rb
class CustomHomepageController < ApplicationController
  requires_login
  
  def interests
    username = params[:username]
    user = User.find_by(username: username)
    
    if user
      render json: {
        interests: user.custom_fields['interests']
      }
    else
      render json: { error: 'User not found' }, status: 404
    end
  end
end
```

إضافة حقل الاهتمامات في تفضيلات المستخدم:
- قم بتعديل قالب تفضيلات المستخدم لتضمين إدخال للاهتمامات.

```html
<!-- plugins/custom_homepage/assets/javascripts/discourse/connectors/user-preferences/interests.hbs -->
<div class="control-group">
  <label class="control-label">{{i18n 'user.preferences.interests'}}</label>
  <div class="controls">
    {{input value=model.custom_fields.interests class="form-control"}}
  </div>
</div>
```

توسيع المسلسل:
- قم بتوسيع مسلسل المستخدم لتضمين حقل الاهتمامات.

```ruby
# plugins/custom_homepage/plugin.rb

after_initialize do
  User.register_custom_field_type('interests', :string)
  
  add_to_serializer(:current_user, :interests) do
    object.custom_fields['interests']
  end

  add_to_serializer(:admin_detailed_user, :interests) do
    object.custom_fields['interests']
  end
end
```

تعديل جافاسكريبت للتعامل مع الاهتمامات:
- استخدم جافاسكريبت لجلب الاهتمامات وحفظها في ملف تعريف المستخدم.

```javascript
// plugins/custom_homepage/assets/javascripts/discourse/initializers/custom-homepage.js.es6

import { withPluginApi } from 'discourse/lib/plugin-api';

export default {
  name: 'custom-homepage',
  initialize(container) {
    withPluginApi('0.8', api => {
      api.modifyClass('controller:preferences/account', {
        save() {
          const interests = this.model.custom_fields.interests;
          this.model.save().then(() => {
            fetch(`/u/${this.model.username}/preferences/interests`, {
              method: 'PUT',
              headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': Discourse.CSRFToken
              },
              body: JSON.stringify({ interests })
            }).then(response => response.json()).then(() => {
              this.flash('Your preferences have been saved.');
            });
          });
        }
      });
    });
  }
};
```
  1. التعامل مع طلب PUT:

    • قم بتنفيذ المنطق للتعامل مع طلب PUT وحفظ الاهتمامات في المتحكم.
    # plugins/custom_homepage/app/controllers/custom_homepage_controller.rb
    class CustomHomepageController < ApplicationController
      requires_login
    
      def interests
        if request.get?
          username = params[:username]
          user = User.find_by(username: username)
          
          if user
            render json: {
              interests: user.custom_fields['interests']
            }
          else
            render json: { error: 'User not found' }, status: 404
          end
        elsif request.put?
          user = current_user
          interests = params[:interests]
          user.custom_fields['interests'] = interests
          user.save_custom_fields
          render json: success_json
        end
      end
    end
    
إعجابَين (2)

يبدو مثيراً للاهتمام. قد تجد بعض الأفكار في هذه الإضافة أيضاً.