From 445f6d8a47b011733e1d0d49576a973fe4af2efd Mon Sep 17 00:00:00 2001 From: Ben Langfeld Date: Thu, 14 Oct 2021 18:41:46 -0300 Subject: [PATCH 1/3] Namespace serializers for consuming controller This change moves all serializers into the same namespace (`Api::V1`) as the controllers which consume those serializers. In doing so it fixes a bug which currently breaks almost any operation in staging, most notably user signup, by falling back to `Object#as_json` to serialize all API responses, not complying at all with our API spec. `active_model_serializers` [looks for the serializers in this namespace by default](https://github.com/rails-api/active_model_serializers/blob/v0.9.8/lib/action_controller/serialization.rb#L62-L80), but this worked on Ruby 2.6.5: ``` [1] pry(#)> r = Registration.create!(params)=> #, @errors=[]>, @screen_name="user", @user= #, @user_params= {"email"=>"user@example.com", "password"=>"secret123", "password_confirmation"=>"secret123"}> [2] pry(#)> default_serializer(r)=> RegistrationSerializer ``` Since Ruby 2.6.6, [a change to constant lookup](https://github.com/ruby/ruby/commit/15eba4ed0ebb4e019a037b0af10b34fdbc85e03a) was introduced which means that the appropriate class can't be found: ``` [2] pry(#)> default_serializer(r) => nil [3] pry(#)> ActiveModel::Serializer.serializer_for(r, namespace: namespace_for_serializer) => nil ``` The reason is that while in both Ruby versions, the constant name that we try to look up is namespaced ([This namespacing behaviour is documented](https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/rendering.md#namespace) in later releases, but the behaviour is similar in v0.9.x.): ``` [4] pry(#)> ActiveModel::Serializer.send(:build_serializer_class, r, namespace: namespace_for_serializer) => "Api::V1::RegistrationSerializer" ``` this name [is passed to Object#const_get](https://github.com/rails-api/active_model_serializers/blob/ff1a36ffbc82c6070905707b29978a7b897dea81/lib/active_model/serializable/utils.rb#L6) which behaves more strictly since Ruby 2.6.6: Ruby 2.6.5: ``` [5] pry(#)> Object.const_get "Api::V1::RegistrationSerializer" => RegistrationSerializer ``` Ruby 2.6.6: ``` [5] pry(#)> Object.const_get "Api::V1::RegistrationSerializer" => nil ``` It is considered appropriate to namespace the serializers together with the consuming controllers because together they constitute a cohesive definition of an API version; should an API V2 be introduced, it should likely have distinct serializers. --- .../serializers/api/v1/chart_serializer.rb | 12 ++++ .../api/v1/checkin_condition_serializer.rb | 7 +++ .../serializers/api/v1/checkin_serializer.rb | 55 +++++++++++++++++ .../api/v1/checkin_symptom_serializer.rb | 7 +++ .../api/v1/checkin_trackable_serializer.rb | 7 +++ .../api/v1/checkin_treatment_serializer.rb | 14 +++++ .../serializers/api/v1/comment_serializer.rb | 18 ++++++ .../api/v1/concerns/notificatable.rb | 16 +++++ .../api/v1/concerns/reaction_relatable.rb | 19 ++++++ .../api/v1/concerns/topic_serializable.rb | 16 +++++ .../{ => api/v1}/condition_serializer.rb | 12 ++-- .../serializers/api/v1/country_serializer.rb | 15 +++++ .../api/v1/day_habit_serializer.rb | 7 +++ .../app/serializers/api/v1/dose_serializer.rb | 9 +++ .../api/v1/education_level_serializer.rb | 6 ++ .../api/v1/ethnicity_serializer.rb | 6 ++ .../app/serializers/api/v1/food_serializer.rb | 9 +++ .../v1/harvey_bradshaw_index_serializer.rb | 8 +++ .../api/v1/invitation_serializer.rb | 9 +++ .../api/v1/oracle_request_serializer.rb | 14 +++++ .../oracle_request_with_token_serializer.rb | 13 ++++ .../serializers/api/v1/password_serializer.rb | 32 ++++++++++ .../serializers/api/v1/pattern_serializer.rb | 11 ++++ .../app/serializers/api/v1/post_serializer.rb | 21 +++++++ .../serializers/api/v1/postable_serializer.rb | 60 +++++++++++++++++++ .../serializers/api/v1/profile_serializer.rb | 50 ++++++++++++++++ .../api/v1/promotion_rate_serializer.rb | 7 +++ .../api/v1/ranked_enum_serializer.rb | 7 +++ .../serializers/api/v1/reaction_serializer.rb | 29 +++++++++ .../api/v1/registration_serializer.rb | 13 ++++ .../serializers/api/v1/search_serializer.rb | 9 +++ .../api/v1/searchable_serializer.rb | 15 +++++ .../serializers/api/v1/session_serializer.rb | 37 ++++++++++++ .../app/serializers/api/v1/sex_serializer.rb | 6 ++ .../{ => api/v1}/symptom_serializer.rb | 12 ++-- .../app/serializers/api/v1/tag_serializer.rb | 21 +++++++ .../api/v1/topic_following_serializer.rb | 7 +++ .../api/v1/trackable_serializer.rb | 23 +++++++ .../{ => api/v1}/tracking_serializer.rb | 8 ++- .../{ => api/v1}/treatment_serializer.rb | 12 ++-- .../{ => api/v1}/user_serializer.rb | 20 ++++--- .../serializers/api/v1/weather_serializer.rb | 7 +++ backend/app/serializers/chart_serializer.rb | 8 --- .../checkin_condition_serializer.rb | 3 - backend/app/serializers/checkin_serializer.rb | 51 ---------------- .../serializers/checkin_symptom_serializer.rb | 3 - .../checkin_trackable_serializer.rb | 3 - .../checkin_treatment_serializer.rb | 10 ---- backend/app/serializers/comment_serializer.rb | 14 ----- .../app/serializers/concerns/notificatable.rb | 12 ---- .../concerns/reaction_relatable.rb | 15 ----- .../concerns/topic_serializable.rb | 12 ---- backend/app/serializers/country_serializer.rb | 11 ---- .../app/serializers/day_habit_serializer.rb | 3 - backend/app/serializers/dose_serializer.rb | 5 -- .../serializers/education_level_serializer.rb | 2 - .../app/serializers/ethnicity_serializer.rb | 2 - backend/app/serializers/food_serializer.rb | 5 -- .../harvey_bradshaw_index_serializer.rb | 4 -- .../app/serializers/invitation_serializer.rb | 5 -- .../serializers/oracle_request_serializer.rb | 10 ---- .../oracle_request_with_token_serializer.rb | 9 --- .../app/serializers/password_serializer.rb | 28 --------- backend/app/serializers/pattern_serializer.rb | 7 --- backend/app/serializers/post_serializer.rb | 17 ------ .../app/serializers/postable_serializer.rb | 56 ----------------- backend/app/serializers/profile_serializer.rb | 46 -------------- .../serializers/promotion_rate_serializer.rb | 3 - .../app/serializers/ranked_enum_serializer.rb | 3 - .../app/serializers/reaction_serializer.rb | 25 -------- .../serializers/registration_serializer.rb | 9 --- backend/app/serializers/search_serializer.rb | 5 -- .../app/serializers/searchable_serializer.rb | 11 ---- backend/app/serializers/session_serializer.rb | 33 ---------- backend/app/serializers/sex_serializer.rb | 2 - backend/app/serializers/tag_serializer.rb | 17 ------ .../serializers/topic_following_serializer.rb | 3 - .../app/serializers/trackable_serializer.rb | 19 ------ backend/app/serializers/weather_serializer.rb | 3 - 79 files changed, 664 insertions(+), 496 deletions(-) create mode 100644 backend/app/serializers/api/v1/chart_serializer.rb create mode 100644 backend/app/serializers/api/v1/checkin_condition_serializer.rb create mode 100644 backend/app/serializers/api/v1/checkin_serializer.rb create mode 100644 backend/app/serializers/api/v1/checkin_symptom_serializer.rb create mode 100644 backend/app/serializers/api/v1/checkin_trackable_serializer.rb create mode 100644 backend/app/serializers/api/v1/checkin_treatment_serializer.rb create mode 100644 backend/app/serializers/api/v1/comment_serializer.rb create mode 100644 backend/app/serializers/api/v1/concerns/notificatable.rb create mode 100644 backend/app/serializers/api/v1/concerns/reaction_relatable.rb create mode 100644 backend/app/serializers/api/v1/concerns/topic_serializable.rb rename backend/app/serializers/{ => api/v1}/condition_serializer.rb (64%) create mode 100644 backend/app/serializers/api/v1/country_serializer.rb create mode 100644 backend/app/serializers/api/v1/day_habit_serializer.rb create mode 100644 backend/app/serializers/api/v1/dose_serializer.rb create mode 100644 backend/app/serializers/api/v1/education_level_serializer.rb create mode 100644 backend/app/serializers/api/v1/ethnicity_serializer.rb create mode 100644 backend/app/serializers/api/v1/food_serializer.rb create mode 100644 backend/app/serializers/api/v1/harvey_bradshaw_index_serializer.rb create mode 100644 backend/app/serializers/api/v1/invitation_serializer.rb create mode 100644 backend/app/serializers/api/v1/oracle_request_serializer.rb create mode 100644 backend/app/serializers/api/v1/oracle_request_with_token_serializer.rb create mode 100644 backend/app/serializers/api/v1/password_serializer.rb create mode 100644 backend/app/serializers/api/v1/pattern_serializer.rb create mode 100644 backend/app/serializers/api/v1/post_serializer.rb create mode 100644 backend/app/serializers/api/v1/postable_serializer.rb create mode 100644 backend/app/serializers/api/v1/profile_serializer.rb create mode 100644 backend/app/serializers/api/v1/promotion_rate_serializer.rb create mode 100644 backend/app/serializers/api/v1/ranked_enum_serializer.rb create mode 100644 backend/app/serializers/api/v1/reaction_serializer.rb create mode 100644 backend/app/serializers/api/v1/registration_serializer.rb create mode 100644 backend/app/serializers/api/v1/search_serializer.rb create mode 100644 backend/app/serializers/api/v1/searchable_serializer.rb create mode 100644 backend/app/serializers/api/v1/session_serializer.rb create mode 100644 backend/app/serializers/api/v1/sex_serializer.rb rename backend/app/serializers/{ => api/v1}/symptom_serializer.rb (64%) create mode 100644 backend/app/serializers/api/v1/tag_serializer.rb create mode 100644 backend/app/serializers/api/v1/topic_following_serializer.rb create mode 100644 backend/app/serializers/api/v1/trackable_serializer.rb rename backend/app/serializers/{ => api/v1}/tracking_serializer.rb (66%) rename backend/app/serializers/{ => api/v1}/treatment_serializer.rb (64%) rename backend/app/serializers/{ => api/v1}/user_serializer.rb (72%) create mode 100644 backend/app/serializers/api/v1/weather_serializer.rb delete mode 100644 backend/app/serializers/chart_serializer.rb delete mode 100644 backend/app/serializers/checkin_condition_serializer.rb delete mode 100644 backend/app/serializers/checkin_serializer.rb delete mode 100644 backend/app/serializers/checkin_symptom_serializer.rb delete mode 100644 backend/app/serializers/checkin_trackable_serializer.rb delete mode 100644 backend/app/serializers/checkin_treatment_serializer.rb delete mode 100644 backend/app/serializers/comment_serializer.rb delete mode 100644 backend/app/serializers/concerns/notificatable.rb delete mode 100644 backend/app/serializers/concerns/reaction_relatable.rb delete mode 100644 backend/app/serializers/concerns/topic_serializable.rb delete mode 100644 backend/app/serializers/country_serializer.rb delete mode 100644 backend/app/serializers/day_habit_serializer.rb delete mode 100644 backend/app/serializers/dose_serializer.rb delete mode 100644 backend/app/serializers/education_level_serializer.rb delete mode 100644 backend/app/serializers/ethnicity_serializer.rb delete mode 100644 backend/app/serializers/food_serializer.rb delete mode 100644 backend/app/serializers/harvey_bradshaw_index_serializer.rb delete mode 100644 backend/app/serializers/invitation_serializer.rb delete mode 100644 backend/app/serializers/oracle_request_serializer.rb delete mode 100644 backend/app/serializers/oracle_request_with_token_serializer.rb delete mode 100644 backend/app/serializers/password_serializer.rb delete mode 100644 backend/app/serializers/pattern_serializer.rb delete mode 100644 backend/app/serializers/post_serializer.rb delete mode 100644 backend/app/serializers/postable_serializer.rb delete mode 100644 backend/app/serializers/profile_serializer.rb delete mode 100644 backend/app/serializers/promotion_rate_serializer.rb delete mode 100644 backend/app/serializers/ranked_enum_serializer.rb delete mode 100644 backend/app/serializers/reaction_serializer.rb delete mode 100644 backend/app/serializers/registration_serializer.rb delete mode 100644 backend/app/serializers/search_serializer.rb delete mode 100644 backend/app/serializers/searchable_serializer.rb delete mode 100644 backend/app/serializers/session_serializer.rb delete mode 100644 backend/app/serializers/sex_serializer.rb delete mode 100644 backend/app/serializers/tag_serializer.rb delete mode 100644 backend/app/serializers/topic_following_serializer.rb delete mode 100644 backend/app/serializers/trackable_serializer.rb delete mode 100644 backend/app/serializers/weather_serializer.rb diff --git a/backend/app/serializers/api/v1/chart_serializer.rb b/backend/app/serializers/api/v1/chart_serializer.rb new file mode 100644 index 000000000..33c8cf237 --- /dev/null +++ b/backend/app/serializers/api/v1/chart_serializer.rb @@ -0,0 +1,12 @@ +module Api + module V1 + class ChartSerializer < ApplicationSerializer + attributes :id, + :start_at, + :end_at + + has_many :checkins, embed: :ids, embed_in_root: true + has_many :trackables, embed: :objects + end + end +end diff --git a/backend/app/serializers/api/v1/checkin_condition_serializer.rb b/backend/app/serializers/api/v1/checkin_condition_serializer.rb new file mode 100644 index 000000000..9b19d8ef8 --- /dev/null +++ b/backend/app/serializers/api/v1/checkin_condition_serializer.rb @@ -0,0 +1,7 @@ +module Api + module V1 + class CheckinConditionSerializer < CheckinTrackableSerializer + attributes :condition_id + end + end +end diff --git a/backend/app/serializers/api/v1/checkin_serializer.rb b/backend/app/serializers/api/v1/checkin_serializer.rb new file mode 100644 index 000000000..d986a3cf2 --- /dev/null +++ b/backend/app/serializers/api/v1/checkin_serializer.rb @@ -0,0 +1,55 @@ +module Api + module V1 + class CheckinSerializer < ApplicationSerializer + attributes :id, :date, :note, :tag_ids, :food_ids, :postal_code, :available_for_hbi?, :available_for_promotion?, + :location_name, :promotion_skipped_at + + has_many :conditions, embed: :objects, serializer: CheckinConditionSerializer + has_many :symptoms, embed: :objects, serializer: CheckinSymptomSerializer + has_many :treatments, embed: :objects, serializer: CheckinTreatmentSerializer + + has_one :weather, embed_in_root: true + has_many :tags, embed_in_root: true + has_many :foods, embed_in_root: true + + has_one :harvey_bradshaw_index, embed_in_root: true + has_one :promotion_rate, embed_in_root: true + + def harvey_bradshaw_index + object.harvey_bradshaw_index if show_single_relation?(:harveyBradshawIndices) + end + + def promotion_rate + object.promotion_rate if show_single_relation?(:promotionRate) + end + + def weather + object.weather if show_single_relation?(:weathersMeasures) + end + + def location_name + object.position&.location_name + end + + def postal_code + object.position&.postal_code + end + + %w[condition symptom treatment].each do |name| + plural_name = name.pluralize + + define_method(plural_name.to_sym) do + query = object.includes ? {"#{name}_id" => {'$in': (object.includes[plural_name] || []).map(&:to_i)}} : {} + + object.send(plural_name).where(query) + end + end + + private + + def show_single_relation?(key) + !object.includes || (object.includes && object.includes[key].present?) + end + end + end +end diff --git a/backend/app/serializers/api/v1/checkin_symptom_serializer.rb b/backend/app/serializers/api/v1/checkin_symptom_serializer.rb new file mode 100644 index 000000000..ddf4c9778 --- /dev/null +++ b/backend/app/serializers/api/v1/checkin_symptom_serializer.rb @@ -0,0 +1,7 @@ +module Api + module V1 + class CheckinSymptomSerializer < CheckinTrackableSerializer + attributes :symptom_id + end + end +end diff --git a/backend/app/serializers/api/v1/checkin_trackable_serializer.rb b/backend/app/serializers/api/v1/checkin_trackable_serializer.rb new file mode 100644 index 000000000..b62235c88 --- /dev/null +++ b/backend/app/serializers/api/v1/checkin_trackable_serializer.rb @@ -0,0 +1,7 @@ +module Api + module V1 + class CheckinTrackableSerializer < ApplicationSerializer + attributes :checkin_id, :value, :color_id, :position + end + end +end diff --git a/backend/app/serializers/api/v1/checkin_treatment_serializer.rb b/backend/app/serializers/api/v1/checkin_treatment_serializer.rb new file mode 100644 index 000000000..5295cbe76 --- /dev/null +++ b/backend/app/serializers/api/v1/checkin_treatment_serializer.rb @@ -0,0 +1,14 @@ +module Api + module V1 + class CheckinTreatmentSerializer < CheckinTrackableSerializer + attributes :treatment_id, :is_taken + has_one :dose, embed: :object + + private + + def dose + ::Dose.new(name: object.value) if object.value.present? + end + end + end +end diff --git a/backend/app/serializers/api/v1/comment_serializer.rb b/backend/app/serializers/api/v1/comment_serializer.rb new file mode 100644 index 000000000..536a02421 --- /dev/null +++ b/backend/app/serializers/api/v1/comment_serializer.rb @@ -0,0 +1,18 @@ +module Api + module V1 + class CommentSerializer < ApplicationSerializer + include Notificatable + include ReactionRelatable + + attributes :post_id, :body, :user_name, :postable_id, :type + + def type + "comment" + end + + def postable_id + :fake + end + end + end +end diff --git a/backend/app/serializers/api/v1/concerns/notificatable.rb b/backend/app/serializers/api/v1/concerns/notificatable.rb new file mode 100644 index 000000000..e714a5d4a --- /dev/null +++ b/backend/app/serializers/api/v1/concerns/notificatable.rb @@ -0,0 +1,16 @@ +module Api + module V1 + module Notificatable + extend ActiveSupport::Concern + + included do + attributes :notifications + end + + def notifications + return {} unless current_user + object.notifications.where(encrypted_notify_user_id: current_user.encrypted_id).count_by_types + end + end + end +end diff --git a/backend/app/serializers/api/v1/concerns/reaction_relatable.rb b/backend/app/serializers/api/v1/concerns/reaction_relatable.rb new file mode 100644 index 000000000..0afcd050a --- /dev/null +++ b/backend/app/serializers/api/v1/concerns/reaction_relatable.rb @@ -0,0 +1,19 @@ +module Api + module V1 + module ReactionRelatable + extend ActiveSupport::Concern + + included do + attributes :reactions + end + + def reactions + ReactionSerializer.new( + object.reactions.values_count_with_participated(current_user&.encrypted_id), + object.id, + object.class.name + ) + end + end + end +end diff --git a/backend/app/serializers/api/v1/concerns/topic_serializable.rb b/backend/app/serializers/api/v1/concerns/topic_serializable.rb new file mode 100644 index 000000000..12fefa553 --- /dev/null +++ b/backend/app/serializers/api/v1/concerns/topic_serializable.rb @@ -0,0 +1,16 @@ +module Api + module V1 + module TopicSerializable + extend ActiveSupport::Concern + + included do + attributes :id, :tag_ids, :symptom_ids, :condition_ids, :treatment_ids + + has_many :tags, embed_in_root: true + has_many :symptoms, embed_in_root: true + has_many :conditions, embed_in_root: true + has_many :treatments, embed_in_root: true + end + end + end +end diff --git a/backend/app/serializers/condition_serializer.rb b/backend/app/serializers/api/v1/condition_serializer.rb similarity index 64% rename from backend/app/serializers/condition_serializer.rb rename to backend/app/serializers/api/v1/condition_serializer.rb index b19f07574..29d2404eb 100644 --- a/backend/app/serializers/condition_serializer.rb +++ b/backend/app/serializers/api/v1/condition_serializer.rb @@ -9,9 +9,13 @@ # trackable_usages_count :integer default(0) # -class ConditionSerializer < ApplicationSerializer - include SearchableSerializer - include TrackableSerializer +module Api + module V1 + class ConditionSerializer < ApplicationSerializer + include SearchableSerializer + include TrackableSerializer - attributes :id, :name + attributes :id, :name + end + end end diff --git a/backend/app/serializers/api/v1/country_serializer.rb b/backend/app/serializers/api/v1/country_serializer.rb new file mode 100644 index 000000000..8ceb5121a --- /dev/null +++ b/backend/app/serializers/api/v1/country_serializer.rb @@ -0,0 +1,15 @@ +module Api + module V1 + class CountrySerializer < ApplicationSerializer + attributes :id, :name + + def id + object.alpha2 + end + + def name + object.translation(I18n.locale.to_s) + end + end + end +end diff --git a/backend/app/serializers/api/v1/day_habit_serializer.rb b/backend/app/serializers/api/v1/day_habit_serializer.rb new file mode 100644 index 000000000..dba27771d --- /dev/null +++ b/backend/app/serializers/api/v1/day_habit_serializer.rb @@ -0,0 +1,7 @@ +module Api + module V1 + class DayHabitSerializer < RankedEnumSerializer + attributes :description + end + end +end diff --git a/backend/app/serializers/api/v1/dose_serializer.rb b/backend/app/serializers/api/v1/dose_serializer.rb new file mode 100644 index 000000000..a02791e66 --- /dev/null +++ b/backend/app/serializers/api/v1/dose_serializer.rb @@ -0,0 +1,9 @@ +module Api + module V1 + class DoseSerializer < ApplicationSerializer + include SearchableSerializer + + attributes :id, :name + end + end +end diff --git a/backend/app/serializers/api/v1/education_level_serializer.rb b/backend/app/serializers/api/v1/education_level_serializer.rb new file mode 100644 index 000000000..5bc75a906 --- /dev/null +++ b/backend/app/serializers/api/v1/education_level_serializer.rb @@ -0,0 +1,6 @@ +module Api + module V1 + class EducationLevelSerializer < RankedEnumSerializer + end + end +end diff --git a/backend/app/serializers/api/v1/ethnicity_serializer.rb b/backend/app/serializers/api/v1/ethnicity_serializer.rb new file mode 100644 index 000000000..356a370e6 --- /dev/null +++ b/backend/app/serializers/api/v1/ethnicity_serializer.rb @@ -0,0 +1,6 @@ +module Api + module V1 + class EthnicitySerializer < RankedEnumSerializer + end + end +end diff --git a/backend/app/serializers/api/v1/food_serializer.rb b/backend/app/serializers/api/v1/food_serializer.rb new file mode 100644 index 000000000..8b0805016 --- /dev/null +++ b/backend/app/serializers/api/v1/food_serializer.rb @@ -0,0 +1,9 @@ +module Api + module V1 + class FoodSerializer < ApplicationSerializer + include SearchableSerializer + + attributes :id, :name + end + end +end diff --git a/backend/app/serializers/api/v1/harvey_bradshaw_index_serializer.rb b/backend/app/serializers/api/v1/harvey_bradshaw_index_serializer.rb new file mode 100644 index 000000000..da27b5742 --- /dev/null +++ b/backend/app/serializers/api/v1/harvey_bradshaw_index_serializer.rb @@ -0,0 +1,8 @@ +module Api + module V1 + class HarveyBradshawIndexSerializer < ApplicationSerializer + attributes :id, :abdominal_mass, :abdominal_pain, :abscess, :anal_fissure, :aphthous_ulcers, :arthralgia, :score, + :erythema_nodosum, :new_fistula, :pyoderma_gangrenosum, :stools, :uveitis, :well_being, :checkin_id + end + end +end diff --git a/backend/app/serializers/api/v1/invitation_serializer.rb b/backend/app/serializers/api/v1/invitation_serializer.rb new file mode 100644 index 000000000..7caf00a6c --- /dev/null +++ b/backend/app/serializers/api/v1/invitation_serializer.rb @@ -0,0 +1,9 @@ +module Api + module V1 + class InvitationSerializer < ApplicationSerializer + attributes :id, :email + + has_one :user, embed_in_root: true + end + end +end diff --git a/backend/app/serializers/api/v1/oracle_request_serializer.rb b/backend/app/serializers/api/v1/oracle_request_serializer.rb new file mode 100644 index 000000000..392452eb2 --- /dev/null +++ b/backend/app/serializers/api/v1/oracle_request_serializer.rb @@ -0,0 +1,14 @@ +module Api + module V1 + class OracleRequestSerializer < ApplicationSerializer + attributes :id, :age, :sex_id, :symptom_ids, :responce, :can_edit + + has_one :sex, embed_in_root: true + has_many :symptoms, embed_in_root: true + + def can_edit + object.can_edit?(scope) + end + end + end +end diff --git a/backend/app/serializers/api/v1/oracle_request_with_token_serializer.rb b/backend/app/serializers/api/v1/oracle_request_with_token_serializer.rb new file mode 100644 index 000000000..edfd7c2bf --- /dev/null +++ b/backend/app/serializers/api/v1/oracle_request_with_token_serializer.rb @@ -0,0 +1,13 @@ +module Api + module V1 + class OracleRequestWithTokenSerializer < OracleRequestSerializer + self.root = :oracle_request + + attributes :token + + def can_edit + true + end + end + end +end diff --git a/backend/app/serializers/api/v1/password_serializer.rb b/backend/app/serializers/api/v1/password_serializer.rb new file mode 100644 index 000000000..eb74f53cd --- /dev/null +++ b/backend/app/serializers/api/v1/password_serializer.rb @@ -0,0 +1,32 @@ +module Api + module V1 + class PasswordSerializer < ApplicationSerializer + attributes :id, :email, :reset_password_token, :current_password, :password, :password_confirmation + + def id + if reset_password_token.present? + reset_password_token + else + Digest::SHA256.base64digest(DateTime.current.to_s) + end + end + + def email + object.try :email + end + + def reset_password_token + serialization_options[:token] + end + + def password + end + + def password_confirmation + end + + def current_password + end + end + end +end diff --git a/backend/app/serializers/api/v1/pattern_serializer.rb b/backend/app/serializers/api/v1/pattern_serializer.rb new file mode 100644 index 000000000..faa759960 --- /dev/null +++ b/backend/app/serializers/api/v1/pattern_serializer.rb @@ -0,0 +1,11 @@ +module Api + module V1 + class PatternSerializer < ApplicationSerializer + attributes :id, :start_at, :end_at, :name, :includes, :author_name + + def author_name + object.author.screen_name + end + end + end +end diff --git a/backend/app/serializers/api/v1/post_serializer.rb b/backend/app/serializers/api/v1/post_serializer.rb new file mode 100644 index 000000000..d09e6cf39 --- /dev/null +++ b/backend/app/serializers/api/v1/post_serializer.rb @@ -0,0 +1,21 @@ +module Api + module V1 + class PostSerializer < ApplicationSerializer + include Notificatable + include TopicSerializable + include ReactionRelatable + + attributes :id, :body, :title, :type, :user_name, :comments_count, :postable_id, :priority + + has_many :comments, embed: :ids + + def type + "post" + end + + def priority + object.try(:priority) + end + end + end +end diff --git a/backend/app/serializers/api/v1/postable_serializer.rb b/backend/app/serializers/api/v1/postable_serializer.rb new file mode 100644 index 000000000..e26d4ea06 --- /dev/null +++ b/backend/app/serializers/api/v1/postable_serializer.rb @@ -0,0 +1,60 @@ +module Api + module V1 + class PostableSerializer + FAKE_ID = "fake".freeze + + attr_reader :postables, :tag_ids, :symptom_ids, :condition_ids, :treatment_ids, :postable_post_ids, :current_user + + def initialize(postables, current_user) + @postables = postables + @current_user = current_user + end + + def as_json(_opts = {}) + posts = [] + comments = [] + + postables.each { |postable| (postable.is_a?(Post) ? posts : comments) << postable } + + prepare_ids(posts) + + posts.concat(Post.where(:id.in => comments.map(&:post_id) - posts.map(&:id))) + + { + postables: [{ + id: FAKE_ID, + post_ids: postable_post_ids, + comment_ids: comments.map { |o| o.id.to_s } + }], + tags: ActiveModel::ArraySerializer.new(Tag.where(id: tag_ids), {}), + posts: ActiveModel::ArraySerializer.new(posts, scope: current_user), + comments: ActiveModel::ArraySerializer.new(comments, scope: current_user), + conditions: ActiveModel::ArraySerializer.new(Condition.where(id: condition_ids), {}), + symptoms: ActiveModel::ArraySerializer.new(Symptom.where(id: symptom_ids), {}), + treatments: ActiveModel::ArraySerializer.new(Treatment.where(id: treatment_ids), {}) + } + end + + private + + def prepare_ids(posts) + @tag_ids = [] + @symptom_ids = [] + @condition_ids = [] + @treatment_ids = [] + @postable_post_ids = [] + + posts.each do |post| + @postable_post_ids << post.id.to_s + + @tag_ids.concat(post.tag_ids) + @symptom_ids.concat(post.symptom_ids) + @condition_ids.concat(post.condition_ids) + @treatment_ids.concat(post.treatment_ids) + + post.postable_id = FAKE_ID + end + end + end + end +end diff --git a/backend/app/serializers/api/v1/profile_serializer.rb b/backend/app/serializers/api/v1/profile_serializer.rb new file mode 100644 index 000000000..e37a864c9 --- /dev/null +++ b/backend/app/serializers/api/v1/profile_serializer.rb @@ -0,0 +1,50 @@ +# == Schema Information +# +# Table name: profiles +# +# id :integer not null, primary key +# user_id :integer +# country_id :string +# birth_date :date +# sex_id :string +# onboarding_step_id :string +# created_at :datetime not null +# updated_at :datetime not null +# ethnicity_ids_string :string +# day_habit_id :string +# education_level_id :string +# day_walking_hours :integer +# most_recent_doses :hstore +# screen_name :string +# most_recent_conditions_positions :hstore +# most_recent_symptoms_positions :hstore +# most_recent_treatments_positions :hstore +# + +module Api + module V1 + class ProfileSerializer < ApplicationSerializer + attributes :id, :screen_name, :birth_date, :country_id, :sex_id, :onboarding_step_id, + :ethnicity_ids, :day_habit_id, :education_level_id, :day_walking_hours, + :pressure_units, :temperature_units, :beta_tester, :notify_token, :notify, :checkin_reminder, + :checkin_reminder_at, :time_zone_name, :notify_top_posts + + def checkin_reminder_at + {hours: serialized_time[0], minutes: serialized_time[1]} + end + + def time_zone_name + time_zone_name = object.time_zone_name + + return Profile::TIMEZONE_PARAMS[:time_zone_name] if time_zone_name.nil? || time_zone_name&.empty? + time_zone_name + end + + def serialized_time + reminder_at = object.checkin_reminder_at + + reminder_at.blank? ? Profile::TIMEZONE_PARAMS[:time] : reminder_at.strftime("%H:%M").split(":") + end + end + end +end diff --git a/backend/app/serializers/api/v1/promotion_rate_serializer.rb b/backend/app/serializers/api/v1/promotion_rate_serializer.rb new file mode 100644 index 000000000..65ef2c3a6 --- /dev/null +++ b/backend/app/serializers/api/v1/promotion_rate_serializer.rb @@ -0,0 +1,7 @@ +module Api + module V1 + class PromotionRateSerializer < ApplicationSerializer + attributes :id, :score, :feedback, :checkin_id + end + end +end diff --git a/backend/app/serializers/api/v1/ranked_enum_serializer.rb b/backend/app/serializers/api/v1/ranked_enum_serializer.rb new file mode 100644 index 000000000..ab7366aa8 --- /dev/null +++ b/backend/app/serializers/api/v1/ranked_enum_serializer.rb @@ -0,0 +1,7 @@ +module Api + module V1 + class RankedEnumSerializer < ApplicationSerializer + attributes :id, :name, :rank + end + end +end diff --git a/backend/app/serializers/api/v1/reaction_serializer.rb b/backend/app/serializers/api/v1/reaction_serializer.rb new file mode 100644 index 000000000..90fdbf94b --- /dev/null +++ b/backend/app/serializers/api/v1/reaction_serializer.rb @@ -0,0 +1,29 @@ +module Api + module V1 + class ReactionSerializer + attr_reader :reactions, :reactable_id, :reactable_type + + def initialize(reactions, reactable_id, reactable_type) + @reactions = reactions + @reactable_id = reactable_id + @reactable_type = reactable_type + end + + def as_json(_opts = {}) + reactions.map { |reaction| serialized_reaction(reaction) } + end + + def serialize_one + { + reaction: serialized_reaction(reactions.first) + } + end + + private + + def serialized_reaction(raw_reaction) + raw_reaction.merge(reactable_id: reactable_id, reactable_type: reactable_type) + end + end + end +end diff --git a/backend/app/serializers/api/v1/registration_serializer.rb b/backend/app/serializers/api/v1/registration_serializer.rb new file mode 100644 index 000000000..2c6788f01 --- /dev/null +++ b/backend/app/serializers/api/v1/registration_serializer.rb @@ -0,0 +1,13 @@ +module Api + module V1 + class RegistrationSerializer < ApplicationSerializer + has_one :user, embed_in_root: true + + private + + def id + object.user.id + end + end + end +end diff --git a/backend/app/serializers/api/v1/search_serializer.rb b/backend/app/serializers/api/v1/search_serializer.rb new file mode 100644 index 000000000..c8f44d806 --- /dev/null +++ b/backend/app/serializers/api/v1/search_serializer.rb @@ -0,0 +1,9 @@ +module Api + module V1 + class SearchSerializer < ApplicationSerializer + attributes :id + + has_many :searchables, embed: :objects + end + end +end diff --git a/backend/app/serializers/api/v1/searchable_serializer.rb b/backend/app/serializers/api/v1/searchable_serializer.rb new file mode 100644 index 000000000..7315d19ad --- /dev/null +++ b/backend/app/serializers/api/v1/searchable_serializer.rb @@ -0,0 +1,15 @@ +module Api + module V1 + module SearchableSerializer + extend ActiveSupport::Concern + + included do + attributes :type + end + + def type + object.class.name.demodulize.downcase.dasherize + end + end + end +end diff --git a/backend/app/serializers/api/v1/session_serializer.rb b/backend/app/serializers/api/v1/session_serializer.rb new file mode 100644 index 000000000..dc4e36523 --- /dev/null +++ b/backend/app/serializers/api/v1/session_serializer.rb @@ -0,0 +1,37 @@ +module Api + module V1 + class SessionSerializer < ApplicationSerializer + attributes :id, + :user_id, + :email, + :token, + :settings + + def id + 1 + end + + def user_id + object.try :id + end + + def email + object.try :email + end + + def token + object.try :authentication_token + end + + def settings + { + base_url: ENV["BASE_URL"], + notification_channel: object.try(:notification_channel), + facebook_app_id: ENV["FACEBOOK_APP_ID"], + discourse_url: Flaredown.config.discourse_url, + discourse_enabled: Flaredown.config.discourse_enabled? + } + end + end + end +end diff --git a/backend/app/serializers/api/v1/sex_serializer.rb b/backend/app/serializers/api/v1/sex_serializer.rb new file mode 100644 index 000000000..ed41a3a1f --- /dev/null +++ b/backend/app/serializers/api/v1/sex_serializer.rb @@ -0,0 +1,6 @@ +module Api + module V1 + class SexSerializer < RankedEnumSerializer + end + end +end diff --git a/backend/app/serializers/symptom_serializer.rb b/backend/app/serializers/api/v1/symptom_serializer.rb similarity index 64% rename from backend/app/serializers/symptom_serializer.rb rename to backend/app/serializers/api/v1/symptom_serializer.rb index ceab4537e..1853118b6 100644 --- a/backend/app/serializers/symptom_serializer.rb +++ b/backend/app/serializers/api/v1/symptom_serializer.rb @@ -9,9 +9,13 @@ # trackable_usages_count :integer default(0) # -class SymptomSerializer < ApplicationSerializer - include SearchableSerializer - include TrackableSerializer +module Api + module V1 + class SymptomSerializer < ApplicationSerializer + include SearchableSerializer + include TrackableSerializer - attributes :id, :name + attributes :id, :name + end + end end diff --git a/backend/app/serializers/api/v1/tag_serializer.rb b/backend/app/serializers/api/v1/tag_serializer.rb new file mode 100644 index 000000000..78314fd28 --- /dev/null +++ b/backend/app/serializers/api/v1/tag_serializer.rb @@ -0,0 +1,21 @@ +# == Schema Information +# +# Table name: tags +# +# id :integer not null, primary key +# created_at :datetime not null +# updated_at :datetime not null +# + +module Api + module V1 + class TagSerializer < ApplicationSerializer + include SearchableSerializer + attributes :id, :name, :users_count + + def users_count + object.trackable_usages_count + end + end + end +end diff --git a/backend/app/serializers/api/v1/topic_following_serializer.rb b/backend/app/serializers/api/v1/topic_following_serializer.rb new file mode 100644 index 000000000..f41e7215a --- /dev/null +++ b/backend/app/serializers/api/v1/topic_following_serializer.rb @@ -0,0 +1,7 @@ +module Api + module V1 + class TopicFollowingSerializer < ApplicationSerializer + include TopicSerializable + end + end +end diff --git a/backend/app/serializers/api/v1/trackable_serializer.rb b/backend/app/serializers/api/v1/trackable_serializer.rb new file mode 100644 index 000000000..922b9e470 --- /dev/null +++ b/backend/app/serializers/api/v1/trackable_serializer.rb @@ -0,0 +1,23 @@ +module Api + module V1 + module TrackableSerializer + extend ActiveSupport::Concern + + included do + attributes :color_id, :type, :users_count + end + + def color_id + @color_id ||= Tracking.find_by(user: current_user, trackable: object).try :color_id + end + + def type + object.class.name.downcase.dasherize + end + + def users_count + object.trackable_usages_count + end + end + end +end diff --git a/backend/app/serializers/tracking_serializer.rb b/backend/app/serializers/api/v1/tracking_serializer.rb similarity index 66% rename from backend/app/serializers/tracking_serializer.rb rename to backend/app/serializers/api/v1/tracking_serializer.rb index 5b2733726..43fc82fea 100644 --- a/backend/app/serializers/tracking_serializer.rb +++ b/backend/app/serializers/api/v1/tracking_serializer.rb @@ -13,6 +13,10 @@ # updated_at :datetime not null # -class TrackingSerializer < ApplicationSerializer - attributes :id, :user_id, :trackable_id, :trackable_type, :start_at, :end_at, :color_id +module Api + module V1 + class TrackingSerializer < ApplicationSerializer + attributes :id, :user_id, :trackable_id, :trackable_type, :start_at, :end_at, :color_id + end + end end diff --git a/backend/app/serializers/treatment_serializer.rb b/backend/app/serializers/api/v1/treatment_serializer.rb similarity index 64% rename from backend/app/serializers/treatment_serializer.rb rename to backend/app/serializers/api/v1/treatment_serializer.rb index 7cda9c3ad..159788d68 100644 --- a/backend/app/serializers/treatment_serializer.rb +++ b/backend/app/serializers/api/v1/treatment_serializer.rb @@ -9,9 +9,13 @@ # trackable_usages_count :integer default(0) # -class TreatmentSerializer < ApplicationSerializer - include SearchableSerializer - include TrackableSerializer +module Api + module V1 + class TreatmentSerializer < ApplicationSerializer + include SearchableSerializer + include TrackableSerializer - attributes :id, :name + attributes :id, :name + end + end end diff --git a/backend/app/serializers/user_serializer.rb b/backend/app/serializers/api/v1/user_serializer.rb similarity index 72% rename from backend/app/serializers/user_serializer.rb rename to backend/app/serializers/api/v1/user_serializer.rb index 02731f385..4ada9bf23 100644 --- a/backend/app/serializers/user_serializer.rb +++ b/backend/app/serializers/api/v1/user_serializer.rb @@ -25,16 +25,20 @@ # updated_at :datetime not null # -class UserSerializer < ApplicationSerializer - attributes :id, :email, :intercom_hash, :topic_following_id +module Api + module V1 + class UserSerializer < ApplicationSerializer + attributes :id, :email, :intercom_hash, :topic_following_id - has_one :profile, embed_in_root: true + has_one :profile, embed_in_root: true - def topic_following_id - object.topic_following.id - end + def topic_following_id + object.topic_following.id + end - def intercom_hash - OpenSSL::HMAC.hexdigest("sha256", ENV["INTERCOM_SECRET"], object.email) + def intercom_hash + OpenSSL::HMAC.hexdigest("sha256", ENV["INTERCOM_SECRET"], object.email) + end + end end end diff --git a/backend/app/serializers/api/v1/weather_serializer.rb b/backend/app/serializers/api/v1/weather_serializer.rb new file mode 100644 index 000000000..441f43a70 --- /dev/null +++ b/backend/app/serializers/api/v1/weather_serializer.rb @@ -0,0 +1,7 @@ +module Api + module V1 + class WeatherSerializer < ApplicationSerializer + attributes :id, :humidity, :icon, :precip_intensity, :pressure, :summary, :temperature_max, :temperature_min + end + end +end diff --git a/backend/app/serializers/chart_serializer.rb b/backend/app/serializers/chart_serializer.rb deleted file mode 100644 index 4cd28e676..000000000 --- a/backend/app/serializers/chart_serializer.rb +++ /dev/null @@ -1,8 +0,0 @@ -class ChartSerializer < ApplicationSerializer - attributes :id, - :start_at, - :end_at - - has_many :checkins, embed: :ids, embed_in_root: true - has_many :trackables, embed: :objects -end diff --git a/backend/app/serializers/checkin_condition_serializer.rb b/backend/app/serializers/checkin_condition_serializer.rb deleted file mode 100644 index 4cd5caec0..000000000 --- a/backend/app/serializers/checkin_condition_serializer.rb +++ /dev/null @@ -1,3 +0,0 @@ -class CheckinConditionSerializer < CheckinTrackableSerializer - attributes :condition_id -end diff --git a/backend/app/serializers/checkin_serializer.rb b/backend/app/serializers/checkin_serializer.rb deleted file mode 100644 index 118d8f25b..000000000 --- a/backend/app/serializers/checkin_serializer.rb +++ /dev/null @@ -1,51 +0,0 @@ -class CheckinSerializer < ApplicationSerializer - attributes :id, :date, :note, :tag_ids, :food_ids, :postal_code, :available_for_hbi?, :available_for_promotion?, - :location_name, :promotion_skipped_at - - has_many :conditions, embed: :objects, serializer: CheckinConditionSerializer - has_many :symptoms, embed: :objects, serializer: CheckinSymptomSerializer - has_many :treatments, embed: :objects, serializer: CheckinTreatmentSerializer - - has_one :weather, embed_in_root: true - has_many :tags, embed_in_root: true - has_many :foods, embed_in_root: true - - has_one :harvey_bradshaw_index, embed_in_root: true - has_one :promotion_rate, embed_in_root: true - - def harvey_bradshaw_index - object.harvey_bradshaw_index if show_single_relation?(:harveyBradshawIndices) - end - - def promotion_rate - object.promotion_rate if show_single_relation?(:promotionRate) - end - - def weather - object.weather if show_single_relation?(:weathersMeasures) - end - - def location_name - object.position&.location_name - end - - def postal_code - object.position&.postal_code - end - - %w[condition symptom treatment].each do |name| - plural_name = name.pluralize - - define_method(plural_name.to_sym) do - query = object.includes ? {"#{name}_id" => {'$in': (object.includes[plural_name] || []).map(&:to_i)}} : {} - - object.send(plural_name).where(query) - end - end - - private - - def show_single_relation?(key) - !object.includes || (object.includes && object.includes[key].present?) - end -end diff --git a/backend/app/serializers/checkin_symptom_serializer.rb b/backend/app/serializers/checkin_symptom_serializer.rb deleted file mode 100644 index 48f5f3d60..000000000 --- a/backend/app/serializers/checkin_symptom_serializer.rb +++ /dev/null @@ -1,3 +0,0 @@ -class CheckinSymptomSerializer < CheckinTrackableSerializer - attributes :symptom_id -end diff --git a/backend/app/serializers/checkin_trackable_serializer.rb b/backend/app/serializers/checkin_trackable_serializer.rb deleted file mode 100644 index 90485a688..000000000 --- a/backend/app/serializers/checkin_trackable_serializer.rb +++ /dev/null @@ -1,3 +0,0 @@ -class CheckinTrackableSerializer < ApplicationSerializer - attributes :checkin_id, :value, :color_id, :position -end diff --git a/backend/app/serializers/checkin_treatment_serializer.rb b/backend/app/serializers/checkin_treatment_serializer.rb deleted file mode 100644 index 6d5612634..000000000 --- a/backend/app/serializers/checkin_treatment_serializer.rb +++ /dev/null @@ -1,10 +0,0 @@ -class CheckinTreatmentSerializer < CheckinTrackableSerializer - attributes :treatment_id, :is_taken - has_one :dose, embed: :object - - private - - def dose - ::Dose.new(name: object.value) if object.value.present? - end -end diff --git a/backend/app/serializers/comment_serializer.rb b/backend/app/serializers/comment_serializer.rb deleted file mode 100644 index 73bfdcfdf..000000000 --- a/backend/app/serializers/comment_serializer.rb +++ /dev/null @@ -1,14 +0,0 @@ -class CommentSerializer < ApplicationSerializer - include Notificatable - include ReactionRelatable - - attributes :post_id, :body, :user_name, :postable_id, :type - - def type - "comment" - end - - def postable_id - :fake - end -end diff --git a/backend/app/serializers/concerns/notificatable.rb b/backend/app/serializers/concerns/notificatable.rb deleted file mode 100644 index 1525ab468..000000000 --- a/backend/app/serializers/concerns/notificatable.rb +++ /dev/null @@ -1,12 +0,0 @@ -module Notificatable - extend ActiveSupport::Concern - - included do - attributes :notifications - end - - def notifications - return {} unless current_user - object.notifications.where(encrypted_notify_user_id: current_user.encrypted_id).count_by_types - end -end diff --git a/backend/app/serializers/concerns/reaction_relatable.rb b/backend/app/serializers/concerns/reaction_relatable.rb deleted file mode 100644 index bde7b1f28..000000000 --- a/backend/app/serializers/concerns/reaction_relatable.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ReactionRelatable - extend ActiveSupport::Concern - - included do - attributes :reactions - end - - def reactions - ReactionSerializer.new( - object.reactions.values_count_with_participated(current_user&.encrypted_id), - object.id, - object.class.name - ) - end -end diff --git a/backend/app/serializers/concerns/topic_serializable.rb b/backend/app/serializers/concerns/topic_serializable.rb deleted file mode 100644 index f844405f3..000000000 --- a/backend/app/serializers/concerns/topic_serializable.rb +++ /dev/null @@ -1,12 +0,0 @@ -module TopicSerializable - extend ActiveSupport::Concern - - included do - attributes :id, :tag_ids, :symptom_ids, :condition_ids, :treatment_ids - - has_many :tags, embed_in_root: true - has_many :symptoms, embed_in_root: true - has_many :conditions, embed_in_root: true - has_many :treatments, embed_in_root: true - end -end diff --git a/backend/app/serializers/country_serializer.rb b/backend/app/serializers/country_serializer.rb deleted file mode 100644 index b58c7cbe0..000000000 --- a/backend/app/serializers/country_serializer.rb +++ /dev/null @@ -1,11 +0,0 @@ -class CountrySerializer < ApplicationSerializer - attributes :id, :name - - def id - object.alpha2 - end - - def name - object.translation(I18n.locale.to_s) - end -end diff --git a/backend/app/serializers/day_habit_serializer.rb b/backend/app/serializers/day_habit_serializer.rb deleted file mode 100644 index 3f0096fc3..000000000 --- a/backend/app/serializers/day_habit_serializer.rb +++ /dev/null @@ -1,3 +0,0 @@ -class DayHabitSerializer < RankedEnumSerializer - attributes :description -end diff --git a/backend/app/serializers/dose_serializer.rb b/backend/app/serializers/dose_serializer.rb deleted file mode 100644 index 8a8e58321..000000000 --- a/backend/app/serializers/dose_serializer.rb +++ /dev/null @@ -1,5 +0,0 @@ -class DoseSerializer < ApplicationSerializer - include SearchableSerializer - - attributes :id, :name -end diff --git a/backend/app/serializers/education_level_serializer.rb b/backend/app/serializers/education_level_serializer.rb deleted file mode 100644 index 302841269..000000000 --- a/backend/app/serializers/education_level_serializer.rb +++ /dev/null @@ -1,2 +0,0 @@ -class EducationLevelSerializer < RankedEnumSerializer -end diff --git a/backend/app/serializers/ethnicity_serializer.rb b/backend/app/serializers/ethnicity_serializer.rb deleted file mode 100644 index 3006b67ca..000000000 --- a/backend/app/serializers/ethnicity_serializer.rb +++ /dev/null @@ -1,2 +0,0 @@ -class EthnicitySerializer < RankedEnumSerializer -end diff --git a/backend/app/serializers/food_serializer.rb b/backend/app/serializers/food_serializer.rb deleted file mode 100644 index 80e79a7d1..000000000 --- a/backend/app/serializers/food_serializer.rb +++ /dev/null @@ -1,5 +0,0 @@ -class FoodSerializer < ApplicationSerializer - include SearchableSerializer - - attributes :id, :name -end diff --git a/backend/app/serializers/harvey_bradshaw_index_serializer.rb b/backend/app/serializers/harvey_bradshaw_index_serializer.rb deleted file mode 100644 index 91d9bf311..000000000 --- a/backend/app/serializers/harvey_bradshaw_index_serializer.rb +++ /dev/null @@ -1,4 +0,0 @@ -class HarveyBradshawIndexSerializer < ApplicationSerializer - attributes :id, :abdominal_mass, :abdominal_pain, :abscess, :anal_fissure, :aphthous_ulcers, :arthralgia, :score, - :erythema_nodosum, :new_fistula, :pyoderma_gangrenosum, :stools, :uveitis, :well_being, :checkin_id -end diff --git a/backend/app/serializers/invitation_serializer.rb b/backend/app/serializers/invitation_serializer.rb deleted file mode 100644 index bb6422e4d..000000000 --- a/backend/app/serializers/invitation_serializer.rb +++ /dev/null @@ -1,5 +0,0 @@ -class InvitationSerializer < ApplicationSerializer - attributes :id, :email - - has_one :user, embed_in_root: true -end diff --git a/backend/app/serializers/oracle_request_serializer.rb b/backend/app/serializers/oracle_request_serializer.rb deleted file mode 100644 index ec530a82c..000000000 --- a/backend/app/serializers/oracle_request_serializer.rb +++ /dev/null @@ -1,10 +0,0 @@ -class OracleRequestSerializer < ApplicationSerializer - attributes :id, :age, :sex_id, :symptom_ids, :responce, :can_edit - - has_one :sex, embed_in_root: true - has_many :symptoms, embed_in_root: true - - def can_edit - object.can_edit?(scope) - end -end diff --git a/backend/app/serializers/oracle_request_with_token_serializer.rb b/backend/app/serializers/oracle_request_with_token_serializer.rb deleted file mode 100644 index f1f4bd7a0..000000000 --- a/backend/app/serializers/oracle_request_with_token_serializer.rb +++ /dev/null @@ -1,9 +0,0 @@ -class OracleRequestWithTokenSerializer < OracleRequestSerializer - self.root = :oracle_request - - attributes :token - - def can_edit - true - end -end diff --git a/backend/app/serializers/password_serializer.rb b/backend/app/serializers/password_serializer.rb deleted file mode 100644 index 4eed3251b..000000000 --- a/backend/app/serializers/password_serializer.rb +++ /dev/null @@ -1,28 +0,0 @@ -class PasswordSerializer < ApplicationSerializer - attributes :id, :email, :reset_password_token, :current_password, :password, :password_confirmation - - def id - if reset_password_token.present? - reset_password_token - else - Digest::SHA256.base64digest(DateTime.current.to_s) - end - end - - def email - object.try :email - end - - def reset_password_token - serialization_options[:token] - end - - def password - end - - def password_confirmation - end - - def current_password - end -end diff --git a/backend/app/serializers/pattern_serializer.rb b/backend/app/serializers/pattern_serializer.rb deleted file mode 100644 index 5283087cc..000000000 --- a/backend/app/serializers/pattern_serializer.rb +++ /dev/null @@ -1,7 +0,0 @@ -class PatternSerializer < ApplicationSerializer - attributes :id, :start_at, :end_at, :name, :includes, :author_name - - def author_name - object.author.screen_name - end -end diff --git a/backend/app/serializers/post_serializer.rb b/backend/app/serializers/post_serializer.rb deleted file mode 100644 index ad511b9e9..000000000 --- a/backend/app/serializers/post_serializer.rb +++ /dev/null @@ -1,17 +0,0 @@ -class PostSerializer < ApplicationSerializer - include Notificatable - include TopicSerializable - include ReactionRelatable - - attributes :id, :body, :title, :type, :user_name, :comments_count, :postable_id, :priority - - has_many :comments, embed: :ids - - def type - "post" - end - - def priority - object.try(:priority) - end -end diff --git a/backend/app/serializers/postable_serializer.rb b/backend/app/serializers/postable_serializer.rb deleted file mode 100644 index 306375829..000000000 --- a/backend/app/serializers/postable_serializer.rb +++ /dev/null @@ -1,56 +0,0 @@ -class PostableSerializer - FAKE_ID = "fake".freeze - - attr_reader :postables, :tag_ids, :symptom_ids, :condition_ids, :treatment_ids, :postable_post_ids, :current_user - - def initialize(postables, current_user) - @postables = postables - @current_user = current_user - end - - def as_json(_opts = {}) - posts = [] - comments = [] - - postables.each { |postable| (postable.is_a?(Post) ? posts : comments) << postable } - - prepare_ids(posts) - - posts.concat(Post.where(:id.in => comments.map(&:post_id) - posts.map(&:id))) - - { - postables: [{ - id: FAKE_ID, - post_ids: postable_post_ids, - comment_ids: comments.map { |o| o.id.to_s } - }], - tags: ActiveModel::ArraySerializer.new(Tag.where(id: tag_ids), {}), - posts: ActiveModel::ArraySerializer.new(posts, scope: current_user), - comments: ActiveModel::ArraySerializer.new(comments, scope: current_user), - conditions: ActiveModel::ArraySerializer.new(Condition.where(id: condition_ids), {}), - symptoms: ActiveModel::ArraySerializer.new(Symptom.where(id: symptom_ids), {}), - treatments: ActiveModel::ArraySerializer.new(Treatment.where(id: treatment_ids), {}) - } - end - - private - - def prepare_ids(posts) - @tag_ids = [] - @symptom_ids = [] - @condition_ids = [] - @treatment_ids = [] - @postable_post_ids = [] - - posts.each do |post| - @postable_post_ids << post.id.to_s - - @tag_ids.concat(post.tag_ids) - @symptom_ids.concat(post.symptom_ids) - @condition_ids.concat(post.condition_ids) - @treatment_ids.concat(post.treatment_ids) - - post.postable_id = FAKE_ID - end - end -end diff --git a/backend/app/serializers/profile_serializer.rb b/backend/app/serializers/profile_serializer.rb deleted file mode 100644 index 976414749..000000000 --- a/backend/app/serializers/profile_serializer.rb +++ /dev/null @@ -1,46 +0,0 @@ -# == Schema Information -# -# Table name: profiles -# -# id :integer not null, primary key -# user_id :integer -# country_id :string -# birth_date :date -# sex_id :string -# onboarding_step_id :string -# created_at :datetime not null -# updated_at :datetime not null -# ethnicity_ids_string :string -# day_habit_id :string -# education_level_id :string -# day_walking_hours :integer -# most_recent_doses :hstore -# screen_name :string -# most_recent_conditions_positions :hstore -# most_recent_symptoms_positions :hstore -# most_recent_treatments_positions :hstore -# - -class ProfileSerializer < ApplicationSerializer - attributes :id, :screen_name, :birth_date, :country_id, :sex_id, :onboarding_step_id, - :ethnicity_ids, :day_habit_id, :education_level_id, :day_walking_hours, - :pressure_units, :temperature_units, :beta_tester, :notify_token, :notify, :checkin_reminder, - :checkin_reminder_at, :time_zone_name, :notify_top_posts - - def checkin_reminder_at - {hours: serialized_time[0], minutes: serialized_time[1]} - end - - def time_zone_name - time_zone_name = object.time_zone_name - - return Profile::TIMEZONE_PARAMS[:time_zone_name] if time_zone_name.nil? || time_zone_name&.empty? - time_zone_name - end - - def serialized_time - reminder_at = object.checkin_reminder_at - - reminder_at.blank? ? Profile::TIMEZONE_PARAMS[:time] : reminder_at.strftime("%H:%M").split(":") - end -end diff --git a/backend/app/serializers/promotion_rate_serializer.rb b/backend/app/serializers/promotion_rate_serializer.rb deleted file mode 100644 index 19e3703d5..000000000 --- a/backend/app/serializers/promotion_rate_serializer.rb +++ /dev/null @@ -1,3 +0,0 @@ -class PromotionRateSerializer < ApplicationSerializer - attributes :id, :score, :feedback, :checkin_id -end diff --git a/backend/app/serializers/ranked_enum_serializer.rb b/backend/app/serializers/ranked_enum_serializer.rb deleted file mode 100644 index a9d8f0bf2..000000000 --- a/backend/app/serializers/ranked_enum_serializer.rb +++ /dev/null @@ -1,3 +0,0 @@ -class RankedEnumSerializer < ApplicationSerializer - attributes :id, :name, :rank -end diff --git a/backend/app/serializers/reaction_serializer.rb b/backend/app/serializers/reaction_serializer.rb deleted file mode 100644 index ed017e76b..000000000 --- a/backend/app/serializers/reaction_serializer.rb +++ /dev/null @@ -1,25 +0,0 @@ -class ReactionSerializer - attr_reader :reactions, :reactable_id, :reactable_type - - def initialize(reactions, reactable_id, reactable_type) - @reactions = reactions - @reactable_id = reactable_id - @reactable_type = reactable_type - end - - def as_json(_opts = {}) - reactions.map { |reaction| serialized_reaction(reaction) } - end - - def serialize_one - { - reaction: serialized_reaction(reactions.first) - } - end - - private - - def serialized_reaction(raw_reaction) - raw_reaction.merge(reactable_id: reactable_id, reactable_type: reactable_type) - end -end diff --git a/backend/app/serializers/registration_serializer.rb b/backend/app/serializers/registration_serializer.rb deleted file mode 100644 index f4647cf39..000000000 --- a/backend/app/serializers/registration_serializer.rb +++ /dev/null @@ -1,9 +0,0 @@ -class RegistrationSerializer < ApplicationSerializer - has_one :user, embed_in_root: true - - private - - def id - object.user.id - end -end diff --git a/backend/app/serializers/search_serializer.rb b/backend/app/serializers/search_serializer.rb deleted file mode 100644 index 384a16a11..000000000 --- a/backend/app/serializers/search_serializer.rb +++ /dev/null @@ -1,5 +0,0 @@ -class SearchSerializer < ApplicationSerializer - attributes :id - - has_many :searchables, embed: :objects -end diff --git a/backend/app/serializers/searchable_serializer.rb b/backend/app/serializers/searchable_serializer.rb deleted file mode 100644 index fd675f02d..000000000 --- a/backend/app/serializers/searchable_serializer.rb +++ /dev/null @@ -1,11 +0,0 @@ -module SearchableSerializer - extend ActiveSupport::Concern - - included do - attributes :type - end - - def type - object.class.name.demodulize.downcase.dasherize - end -end diff --git a/backend/app/serializers/session_serializer.rb b/backend/app/serializers/session_serializer.rb deleted file mode 100644 index 95f47e0cc..000000000 --- a/backend/app/serializers/session_serializer.rb +++ /dev/null @@ -1,33 +0,0 @@ -class SessionSerializer < ApplicationSerializer - attributes :id, - :user_id, - :email, - :token, - :settings - - def id - 1 - end - - def user_id - object.try :id - end - - def email - object.try :email - end - - def token - object.try :authentication_token - end - - def settings - { - base_url: ENV["BASE_URL"], - notification_channel: object.try(:notification_channel), - facebook_app_id: ENV["FACEBOOK_APP_ID"], - discourse_url: Flaredown.config.discourse_url, - discourse_enabled: Flaredown.config.discourse_enabled? - } - end -end diff --git a/backend/app/serializers/sex_serializer.rb b/backend/app/serializers/sex_serializer.rb deleted file mode 100644 index 55b633e90..000000000 --- a/backend/app/serializers/sex_serializer.rb +++ /dev/null @@ -1,2 +0,0 @@ -class SexSerializer < RankedEnumSerializer -end diff --git a/backend/app/serializers/tag_serializer.rb b/backend/app/serializers/tag_serializer.rb deleted file mode 100644 index dab382389..000000000 --- a/backend/app/serializers/tag_serializer.rb +++ /dev/null @@ -1,17 +0,0 @@ -# == Schema Information -# -# Table name: tags -# -# id :integer not null, primary key -# created_at :datetime not null -# updated_at :datetime not null -# - -class TagSerializer < ApplicationSerializer - include SearchableSerializer - attributes :id, :name, :users_count - - def users_count - object.trackable_usages_count - end -end diff --git a/backend/app/serializers/topic_following_serializer.rb b/backend/app/serializers/topic_following_serializer.rb deleted file mode 100644 index 684fcb17a..000000000 --- a/backend/app/serializers/topic_following_serializer.rb +++ /dev/null @@ -1,3 +0,0 @@ -class TopicFollowingSerializer < ApplicationSerializer - include TopicSerializable -end diff --git a/backend/app/serializers/trackable_serializer.rb b/backend/app/serializers/trackable_serializer.rb deleted file mode 100644 index 44d6a36bf..000000000 --- a/backend/app/serializers/trackable_serializer.rb +++ /dev/null @@ -1,19 +0,0 @@ -module TrackableSerializer - extend ActiveSupport::Concern - - included do - attributes :color_id, :type, :users_count - end - - def color_id - @color_id ||= Tracking.find_by(user: current_user, trackable: object).try :color_id - end - - def type - object.class.name.downcase.dasherize - end - - def users_count - object.trackable_usages_count - end -end diff --git a/backend/app/serializers/weather_serializer.rb b/backend/app/serializers/weather_serializer.rb deleted file mode 100644 index f5fe233f1..000000000 --- a/backend/app/serializers/weather_serializer.rb +++ /dev/null @@ -1,3 +0,0 @@ -class WeatherSerializer < ApplicationSerializer - attributes :id, :humidity, :icon, :precip_intensity, :pressure, :summary, :temperature_max, :temperature_min -end From 194d1ebe5bf7efc9ab2bc710ca45ecf9f1052f28 Mon Sep 17 00:00:00 2001 From: Ben Langfeld Date: Thu, 14 Oct 2021 19:11:39 -0300 Subject: [PATCH 2/3] Scope controller constant lookups correctly --- .../controllers/api/v1/aws_ses_controller.rb | 38 +++--- .../api/v1/chart_lists_controller.rb | 10 +- .../controllers/api/v1/charts_controller.rb | 46 +++---- .../api/v1/charts_pattern_controller.rb | 40 +++--- .../controllers/api/v1/checkins_controller.rb | 50 ++++---- .../controllers/api/v1/comments_controller.rb | 64 +++++----- .../api/v1/conditions_controller.rb | 44 ++++--- .../api/v1/countries_controller.rb | 48 ++++---- .../v1/data_export_schedules_controller.rb | 12 +- .../api/v1/day_habits_controller.rb | 38 +++--- .../api/v1/discourses_controller.rb | 10 +- .../api/v1/education_levels_controller.rb | 40 +++--- .../api/v1/ethnicities_controller.rb | 38 +++--- .../controllers/api/v1/foods_controller.rb | 62 +++++----- .../v1/harvey_bradshaw_indices_controller.rb | 38 +++--- .../api/v1/invitations_controller.rb | 26 ++-- .../api/v1/notifications_controller.rb | 70 ++++++----- .../api/v1/omniauth_callbacks_controller.rb | 52 ++++---- .../api/v1/oracle_requests_controller.rb | 90 +++++++------- .../api/v1/passwords_controller.rb | 86 ++++++------- .../controllers/api/v1/patterns_controller.rb | 100 +++++++-------- .../api/v1/postables_controller.rb | 26 ++-- .../controllers/api/v1/posts_controller.rb | 70 ++++++----- .../controllers/api/v1/profiles_controller.rb | 108 ++++++++-------- .../api/v1/promotion_rates_controller.rb | 44 ++++--- .../controllers/api/v1/pushers_controller.rb | 22 ++-- .../api/v1/reactions_controller.rb | 116 +++++++++--------- .../api/v1/registrations_controller.rb | 18 +-- .../controllers/api/v1/searches_controller.rb | 48 ++++---- .../controllers/api/v1/sessions_controller.rb | 40 +++--- .../controllers/api/v1/sexes_controller.rb | 38 +++--- .../controllers/api/v1/symptoms_controller.rb | 44 ++++--- .../app/controllers/api/v1/tags_controller.rb | 58 +++++---- .../api/v1/topic_followings_controller.rb | 46 +++---- .../api/v1/trackings_controller.rb | 60 ++++----- .../api/v1/treatments_controller.rb | 44 ++++--- .../api/v1/unsubscribes_controller.rb | 40 +++--- .../controllers/api/v1/users_controller.rb | 28 +++-- .../controllers/api/v1/weathers_controller.rb | 24 ++-- backend/spec/models/food_spec.rb | 4 +- backend/spec/spec_helper.rb | 6 + 41 files changed, 1024 insertions(+), 862 deletions(-) diff --git a/backend/app/controllers/api/v1/aws_ses_controller.rb b/backend/app/controllers/api/v1/aws_ses_controller.rb index 598bef947..a2ca7e465 100644 --- a/backend/app/controllers/api/v1/aws_ses_controller.rb +++ b/backend/app/controllers/api/v1/aws_ses_controller.rb @@ -1,24 +1,28 @@ -class Api::V1::AwsSesController < ApplicationController - skip_authorize_resource only: [:mail_it, :notification] - skip_before_action :authenticate_user!, only: [:mail_it, :notification] +module Api + module V1 + class AwsSesController < ApplicationController + skip_authorize_resource only: [:mail_it, :notification] + skip_before_action :authenticate_user!, only: [:mail_it, :notification] - def notification - message_type = request.headers["x-amz-sns-message-type"] - # sns_topic = request.headers['x-amz-sns-topic-arn'] - raw_post = request.raw_post + def notification + message_type = request.headers["x-amz-sns-message-type"] + # sns_topic = request.headers['x-amz-sns-topic-arn'] + raw_post = request.raw_post - if message_type.include? "Confirmation" - send_subscription_confirmation(raw_post) - elsif message_type.include? "Notification" - EmailRejectDispatcher.perform_async(raw_post) - end + if message_type.include? "Confirmation" + send_subscription_confirmation(raw_post) + elsif message_type.include? "Notification" + EmailRejectDispatcher.perform_async(raw_post) + end - render nothing: true, status: 200 - end + render nothing: true, status: 200 + end - def send_subscription_confirmation(raw_post) - json = JSON.parse(raw_post) + def send_subscription_confirmation(raw_post) + json = JSON.parse(raw_post) - open(json["SubscribeURL"]) + open(json["SubscribeURL"]) + end + end end end diff --git a/backend/app/controllers/api/v1/chart_lists_controller.rb b/backend/app/controllers/api/v1/chart_lists_controller.rb index 4607a4d02..db6b70644 100644 --- a/backend/app/controllers/api/v1/chart_lists_controller.rb +++ b/backend/app/controllers/api/v1/chart_lists_controller.rb @@ -1,5 +1,9 @@ -class Api::V1::ChartListsController < ApplicationController - def show - render json: ChartListService.new(current_user: current_user).as_json +module Api + module V1 + class ChartListsController < ApplicationController + def show + render json: ChartListService.new(current_user: current_user).as_json + end + end end end diff --git a/backend/app/controllers/api/v1/charts_controller.rb b/backend/app/controllers/api/v1/charts_controller.rb index 2ffe34b93..3c9644bb2 100644 --- a/backend/app/controllers/api/v1/charts_controller.rb +++ b/backend/app/controllers/api/v1/charts_controller.rb @@ -1,28 +1,32 @@ -class Api::V1::ChartsController < ApplicationController - def show - chart = Chart.new(chart_params) +module Api + module V1 + class ChartsController < ApplicationController + def show + chart = Chart.new(chart_params) - # FIXME - # rubocop:disable Style/SignalException - fail(ActiveRecord::RecordInvalid, chart) if chart.invalid? - # rubocop:enable Style/SignalException + # FIXME + # rubocop:disable Style/SignalException + fail(ActiveRecord::RecordInvalid, chart) if chart.invalid? + # rubocop:enable Style/SignalException - render json: chart - end + render json: chart + end - def chart_params - includes_params = { - tags: [], - foods: [], - symptoms: [], - conditions: [], - treatments: [], - weathersMeasures: [], - harveyBradshawIndices: [] - } + def chart_params + includes_params = { + tags: [], + foods: [], + symptoms: [], + conditions: [], + treatments: [], + weathersMeasures: [], + harveyBradshawIndices: [] + } - params.permit(:id, :start_at, :end_at, includes: includes_params).tap do |whitelist| - whitelist[:user] = current_user + params.permit(:id, :start_at, :end_at, includes: includes_params).tap do |whitelist| + whitelist[:user] = current_user + end + end end end end diff --git a/backend/app/controllers/api/v1/charts_pattern_controller.rb b/backend/app/controllers/api/v1/charts_pattern_controller.rb index 61545a955..160916988 100644 --- a/backend/app/controllers/api/v1/charts_pattern_controller.rb +++ b/backend/app/controllers/api/v1/charts_pattern_controller.rb @@ -1,27 +1,31 @@ -class Api::V1::ChartsPatternController < ApplicationController - skip_before_action :authenticate_user!, only: [:index] +module Api + module V1 + class ChartsPatternController < ApplicationController + skip_before_action :authenticate_user!, only: [:index] - def index - offset = charts_pattern_params[:offset].to_i - start_at = (charts_pattern_params[:start_at].to_date - offset.days).to_s + def index + offset = charts_pattern_params[:offset].to_i + start_at = (charts_pattern_params[:start_at].to_date - offset.days).to_s - end_date = charts_pattern_params[:end_at].to_date - end_at = (Time.current.to_date == end_date ? end_date : (end_date + offset.days)).to_s + end_date = charts_pattern_params[:end_at].to_date + end_at = (Time.current.to_date == end_date ? end_date : (end_date + offset.days)).to_s - @patterns = Pattern.where(id: {'$in': charts_pattern_params[:pattern_ids] || []}) + @patterns = Pattern.where(id: {'$in': charts_pattern_params[:pattern_ids] || []}) - @extended_patterns = @patterns.map do |pattern| - pattern.extend(PatternExtender).form_chart_data(start_at: start_at, - end_at: end_at, - pattern: pattern) - end + @extended_patterns = @patterns.map do |pattern| + pattern.extend(PatternExtender).form_chart_data(start_at: start_at, + end_at: end_at, + pattern: pattern) + end - render json: @extended_patterns, meta: {color_ids: Flaredown::Colorable::IDS} - end + render json: @extended_patterns, meta: {color_ids: Flaredown::Colorable::IDS} + end - private + private - def charts_pattern_params - params.permit(:start_at, :end_at, :offset, pattern_ids: []) + def charts_pattern_params + params.permit(:start_at, :end_at, :offset, pattern_ids: []) + end + end end end diff --git a/backend/app/controllers/api/v1/checkins_controller.rb b/backend/app/controllers/api/v1/checkins_controller.rb index d1c8a30cc..611aba8ea 100644 --- a/backend/app/controllers/api/v1/checkins_controller.rb +++ b/backend/app/controllers/api/v1/checkins_controller.rb @@ -1,31 +1,35 @@ -class Api::V1::CheckinsController < ApplicationController - def index - date = params[:date] +module Api + module V1 + class CheckinsController < ApplicationController + def index + date = params[:date] - if date.blank? && params.require(:page) - render json: current_user.checkins.where(:note.nin => [nil, ""]).order_by(date: :desc).page(params[:page]).per(10) - else - render json: current_user.checkins.where(date: Date.parse(date)) - end - end + if date.blank? && params.require(:page) + render json: current_user.checkins.where(:note.nin => [nil, ""]).order_by(date: :desc).page(params[:page]).per(10) + else + render json: current_user.checkins.where(date: Date.parse(date)) + end + end - def show - render json: Checkin.find(id) - end + def show + render json: Checkin.find(id) + end - def create - date = params.require(:checkin).require(:date) - checkin = Checkin::Creator.new(current_user.id, Date.parse(date)).create! - render json: checkin - end + def create + date = params.require(:checkin).require(:date) + checkin = Checkin::Creator.new(current_user.id, Date.parse(date)).create! + render json: checkin + end - def update - render json: Checkin::Updater.new(current_user, params).update! - end + def update + render json: Checkin::Updater.new(current_user, params).update! + end - private + private - def id - params.require(:id) + def id + params.require(:id) + end + end end end diff --git a/backend/app/controllers/api/v1/comments_controller.rb b/backend/app/controllers/api/v1/comments_controller.rb index 5bb91ed60..4b0290090 100644 --- a/backend/app/controllers/api/v1/comments_controller.rb +++ b/backend/app/controllers/api/v1/comments_controller.rb @@ -1,41 +1,45 @@ -class Api::V1::CommentsController < ApplicationController - load_and_authorize_resource - skip_before_action :authenticate_user!, only: [:index] +module Api + module V1 + class CommentsController < ApplicationController + load_and_authorize_resource + skip_before_action :authenticate_user!, only: [:index] + + def index + render json: @comments.where(:id.in => params[:ids]).order_by(created_at: :asc) + end - def index - render json: @comments.where(:id.in => params[:ids]).order_by(created_at: :asc) - end + def show + render json: @comment + end - def show - render json: @comment - end + def create + @comment.encrypted_user_id = current_user.encrypted_id + + if @comment.save + UpdatePostCountersJob.perform_async(parent_id: create_params[:post_id], parent_type: "Post") - def create - @comment.encrypted_user_id = current_user.encrypted_id + unless @comment.encrypted_user_id == @comment.post.encrypted_user_id + Notification.create( + kind: :comment, + notificateable: @comment, + encrypted_user_id: @comment.encrypted_user_id, + encrypted_notify_user_id: @comment.post.encrypted_user_id + ) + end - if @comment.save - UpdatePostCountersJob.perform_async(parent_id: create_params[:post_id], parent_type: "Post") + DiscussionMention.perform_async(current_user.encrypted_id, @comment.id.to_s) - unless @comment.encrypted_user_id == @comment.post.encrypted_user_id - Notification.create( - kind: :comment, - notificateable: @comment, - encrypted_user_id: @comment.encrypted_user_id, - encrypted_notify_user_id: @comment.post.encrypted_user_id - ) + render json: @comment, status: :created + else + render json: {errors: @comment.errors}, status: :unprocessable_entity + end end - DiscussionMention.perform_async(current_user.encrypted_id, @comment.id.to_s) + private - render json: @comment, status: :created - else - render json: {errors: @comment.errors}, status: :unprocessable_entity + def create_params + params.require(:comment).permit(:body, :post_id) + end end end - - private - - def create_params - params.require(:comment).permit(:body, :post_id) - end end diff --git a/backend/app/controllers/api/v1/conditions_controller.rb b/backend/app/controllers/api/v1/conditions_controller.rb index e62f56199..74fdd91ff 100644 --- a/backend/app/controllers/api/v1/conditions_controller.rb +++ b/backend/app/controllers/api/v1/conditions_controller.rb @@ -1,29 +1,33 @@ -class Api::V1::ConditionsController < ApplicationController - load_and_authorize_resource - skip_before_action :authenticate_user!, only: [:show] +module Api + module V1 + class ConditionsController < ApplicationController + load_and_authorize_resource + skip_before_action :authenticate_user!, only: [:show] - def index - @conditions = @conditions.includes(:translations) - @conditions = ids.present? ? @conditions.where(id: ids) : @conditions.order(:name).limit(50) + def index + @conditions = @conditions.includes(:translations) + @conditions = ids.present? ? @conditions.where(id: ids) : @conditions.order(:name).limit(50) - render json: @conditions - end + render json: @conditions + end - def show - render json: @condition - end + def show + render json: @condition + end - def create - render json: TrackableCreator.new(@condition, current_user).create! - end + def create + render json: TrackableCreator.new(@condition, current_user).create! + end - private + private - def create_params - params.require(:condition).permit(:name) - end + def create_params + params.require(:condition).permit(:name) + end - def ids - @ids ||= params[:ids] if params[:ids].is_a?(Array) + def ids + @ids ||= params[:ids] if params[:ids].is_a?(Array) + end + end end end diff --git a/backend/app/controllers/api/v1/countries_controller.rb b/backend/app/controllers/api/v1/countries_controller.rb index 46e017baf..da1cc8e86 100644 --- a/backend/app/controllers/api/v1/countries_controller.rb +++ b/backend/app/controllers/api/v1/countries_controller.rb @@ -1,28 +1,32 @@ -class Api::V1::CountriesController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class CountriesController < ApplicationController + skip_before_action :authenticate_user! - def index - render json: Country.all, each_serializer: CountrySerializer, root: false - end + def index + render json: Country.all, each_serializer: CountrySerializer, root: false + end - def show - country = Country.find_country_by_alpha2(alpha2) - # FIXME - # rubocop:disable Style/SignalException - fail ActiveRecord::RecordNotFound if country.nil? - # rubocop:enable Style/SignalException - render json: country, serializer: CountrySerializer - end + def show + country = Country.find_country_by_alpha2(alpha2) + # FIXME + # rubocop:disable Style/SignalException + fail ActiveRecord::RecordNotFound if country.nil? + # rubocop:enable Style/SignalException + render json: country, serializer: CountrySerializer + end - private + private - def alpha2 - id = params.require(:id) - match_data = /^[[:alpha:]]{2}$/.match(id) - # FIXME - # rubocop:disable Style/SignalException - fail(ActionController::BadRequest, "id param must be a 2 alphabetic characters string") if match_data.nil? - # rubocop:enable Style/SignalException - match_data[0] + def alpha2 + id = params.require(:id) + match_data = /^[[:alpha:]]{2}$/.match(id) + # FIXME + # rubocop:disable Style/SignalException + fail(ActionController::BadRequest, "id param must be a 2 alphabetic characters string") if match_data.nil? + # rubocop:enable Style/SignalException + match_data[0] + end + end end end diff --git a/backend/app/controllers/api/v1/data_export_schedules_controller.rb b/backend/app/controllers/api/v1/data_export_schedules_controller.rb index e7f3d43ee..2a74eae11 100644 --- a/backend/app/controllers/api/v1/data_export_schedules_controller.rb +++ b/backend/app/controllers/api/v1/data_export_schedules_controller.rb @@ -1,7 +1,11 @@ -class Api::V1::DataExportSchedulesController < ApplicationController - def create - DataExportJob.perform_later(current_user.id) +module Api + module V1 + class DataExportSchedulesController < ApplicationController + def create + DataExportJob.perform_later(current_user.id) - head :created + head :created + end + end end end diff --git a/backend/app/controllers/api/v1/day_habits_controller.rb b/backend/app/controllers/api/v1/day_habits_controller.rb index 37247f56e..21f68707a 100644 --- a/backend/app/controllers/api/v1/day_habits_controller.rb +++ b/backend/app/controllers/api/v1/day_habits_controller.rb @@ -1,23 +1,27 @@ -class Api::V1::DayHabitsController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class DayHabitsController < ApplicationController + skip_before_action :authenticate_user! - def index - render json: DayHabit.all - end + def index + render json: DayHabit.all + end - def show - day_habit = DayHabit.find(day_habit_id) - render json: day_habit - end + def show + day_habit = DayHabit.find(day_habit_id) + render json: day_habit + end - private + private - def day_habit_id - id = params.require(:id) - # FIXME - # rubocop:disable Style/SignalException - fail(ActionController::BadRequest, "id param is not a valid day_habit id") unless DayHabit.all_ids.include?(id) - # rubocop:enable Style/SignalException - id + def day_habit_id + id = params.require(:id) + # FIXME + # rubocop:disable Style/SignalException + fail(ActionController::BadRequest, "id param is not a valid day_habit id") unless DayHabit.all_ids.include?(id) + # rubocop:enable Style/SignalException + id + end + end end end diff --git a/backend/app/controllers/api/v1/discourses_controller.rb b/backend/app/controllers/api/v1/discourses_controller.rb index 426ea3941..f44125594 100644 --- a/backend/app/controllers/api/v1/discourses_controller.rb +++ b/backend/app/controllers/api/v1/discourses_controller.rb @@ -1,5 +1,9 @@ -class Api::V1::DiscoursesController < ApplicationController - def create - render json: {url: DiscourseClient.new(current_user, params).generate_url} +module Api + module V1 + class DiscoursesController < ApplicationController + def create + render json: {url: DiscourseClient.new(current_user, params).generate_url} + end + end end end diff --git a/backend/app/controllers/api/v1/education_levels_controller.rb b/backend/app/controllers/api/v1/education_levels_controller.rb index 91487c2a1..f742ecb65 100644 --- a/backend/app/controllers/api/v1/education_levels_controller.rb +++ b/backend/app/controllers/api/v1/education_levels_controller.rb @@ -1,25 +1,29 @@ -class Api::V1::EducationLevelsController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class EducationLevelsController < ApplicationController + skip_before_action :authenticate_user! - def index - render json: EducationLevel.all - end + def index + render json: EducationLevel.all + end - def show - education_level = EducationLevel.find(education_level_id) - render json: education_level - end + def show + education_level = EducationLevel.find(education_level_id) + render json: education_level + end - private + private - def education_level_id - id = params.require(:id) - # FIXME - # rubocop:disable Style/SignalException - unless EducationLevel.all_ids.include?(id) - fail(ActionController::BadRequest, "id param is not a valid education_level id") + def education_level_id + id = params.require(:id) + # FIXME + # rubocop:disable Style/SignalException + unless EducationLevel.all_ids.include?(id) + fail(ActionController::BadRequest, "id param is not a valid education_level id") + end + # rubocop:enable Style/SignalException + id + end end - # rubocop:enable Style/SignalException - id end end diff --git a/backend/app/controllers/api/v1/ethnicities_controller.rb b/backend/app/controllers/api/v1/ethnicities_controller.rb index e6fff93d9..f63c5ec35 100644 --- a/backend/app/controllers/api/v1/ethnicities_controller.rb +++ b/backend/app/controllers/api/v1/ethnicities_controller.rb @@ -1,23 +1,27 @@ -class Api::V1::EthnicitiesController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class EthnicitiesController < ApplicationController + skip_before_action :authenticate_user! - def index - render json: Ethnicity.all - end + def index + render json: Ethnicity.all + end - def show - ethnicity = Ethnicity.find(ethnicity_id) - render json: ethnicity - end + def show + ethnicity = Ethnicity.find(ethnicity_id) + render json: ethnicity + end - private + private - def ethnicity_id - id = params.require(:id) - # FIXME - # rubocop:disable Style/SignalException - fail(ActionController::BadRequest, "id param is not a valid ethnicity id") unless Ethnicity.all_ids.include?(id) - # rubocop:enable Style/SignalException - id + def ethnicity_id + id = params.require(:id) + # FIXME + # rubocop:disable Style/SignalException + fail(ActionController::BadRequest, "id param is not a valid ethnicity id") unless Ethnicity.all_ids.include?(id) + # rubocop:enable Style/SignalException + id + end + end end end diff --git a/backend/app/controllers/api/v1/foods_controller.rb b/backend/app/controllers/api/v1/foods_controller.rb index a51e4fee5..ba9e83a4f 100644 --- a/backend/app/controllers/api/v1/foods_controller.rb +++ b/backend/app/controllers/api/v1/foods_controller.rb @@ -1,38 +1,42 @@ -class Api::V1::FoodsController < ApplicationController - load_and_authorize_resource - - def index - @foods = @foods.includes(:translations) - - foods = - if ids.present? - @foods.where(id: ids) - elsif scope.present? - CollectionRetriever.new(Food, scope, current_user).retrieve +module Api + module V1 + class FoodsController < ApplicationController + load_and_authorize_resource + + def index + @foods = @foods.includes(:translations) + + foods = + if ids.present? + @foods.where(id: ids) + elsif scope.present? + CollectionRetriever.new(Food, scope, current_user).retrieve + end + + render json: foods end - render json: foods - end - - def show - render json: @food - end + def show + render json: @food + end - def create - render json: TrackableCreator.new(@food, current_user).create! - end + def create + render json: TrackableCreator.new(@food, current_user).create! + end - private + private - def create_params - {long_desc: params.require(:food).require(:name)} - end + def create_params + {long_desc: params.require(:food).require(:name)} + end - def ids - @ids ||= params[:ids] - end + def ids + @ids ||= params[:ids] + end - def scope - @scope ||= params[:scope]&.to_sym + def scope + @scope ||= params[:scope]&.to_sym + end + end end end diff --git a/backend/app/controllers/api/v1/harvey_bradshaw_indices_controller.rb b/backend/app/controllers/api/v1/harvey_bradshaw_indices_controller.rb index 7e34544b7..4d0f5f602 100644 --- a/backend/app/controllers/api/v1/harvey_bradshaw_indices_controller.rb +++ b/backend/app/controllers/api/v1/harvey_bradshaw_indices_controller.rb @@ -1,24 +1,28 @@ -class Api::V1::HarveyBradshawIndicesController < ApplicationController - load_and_authorize_resource +module Api + module V1 + class HarveyBradshawIndicesController < ApplicationController + load_and_authorize_resource - def show - render json: @harvey_bradshaw_index - end + def show + render json: @harvey_bradshaw_index + end - def create - @harvey_bradshaw_index.save + def create + @harvey_bradshaw_index.save - render json: @harvey_bradshaw_index - end + render json: @harvey_bradshaw_index + end - private + private - def create_params - params.require(:harvey_bradshaw_index).permit( - :abdominal_mass, :abdominal_pain, :abscess, - :anal_fissure, :aphthous_ulcers, :arthralgia, - :checkin_id, :erythema_nodosum, :new_fistula, - :pyoderma_gangrenosum, :stools, :uveitis, :well_being - ) + def create_params + params.require(:harvey_bradshaw_index).permit( + :abdominal_mass, :abdominal_pain, :abscess, + :anal_fissure, :aphthous_ulcers, :arthralgia, + :checkin_id, :erythema_nodosum, :new_fistula, + :pyoderma_gangrenosum, :stools, :uveitis, :well_being + ) + end + end end end diff --git a/backend/app/controllers/api/v1/invitations_controller.rb b/backend/app/controllers/api/v1/invitations_controller.rb index 621a001d5..bc3801634 100644 --- a/backend/app/controllers/api/v1/invitations_controller.rb +++ b/backend/app/controllers/api/v1/invitations_controller.rb @@ -1,15 +1,19 @@ -class Api::V1::InvitationsController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class InvitationsController < ApplicationController + skip_before_action :authenticate_user! - def show - render json: Invitation.find(params[:id]) - end + def show + render json: Invitation.find(params[:id]) + end - def update - invitation = Invitation.find(params[:id]) - invitation.accept!( - params.require(:invitation).permit(:email, :password, :password_confirmation) - ) - render json: invitation + def update + invitation = Invitation.find(params[:id]) + invitation.accept!( + params.require(:invitation).permit(:email, :password, :password_confirmation) + ) + render json: invitation + end + end end end diff --git a/backend/app/controllers/api/v1/notifications_controller.rb b/backend/app/controllers/api/v1/notifications_controller.rb index f5026b5f9..0e4e6d6e9 100644 --- a/backend/app/controllers/api/v1/notifications_controller.rb +++ b/backend/app/controllers/api/v1/notifications_controller.rb @@ -1,48 +1,52 @@ -class Api::V1::NotificationsController < ApplicationController - def index - notifications = Notification.where(encrypted_notify_user_id: current_user.encrypted_id) +module Api + module V1 + class NotificationsController < ApplicationController + def index + notifications = Notification.where(encrypted_notify_user_id: current_user.encrypted_id) - authorize_collection :index, notifications + authorize_collection :index, notifications - render json: {notifications: notifications.aggregated_by_kind_and_subject} - end + render json: {notifications: notifications.aggregated_by_kind_and_subject} + end - def update - notifications = Notification.where(notification_params) + def update + notifications = Notification.where(notification_params) - authorize_collection :update, notifications + authorize_collection :update, notifications - if notifications.update_all(unread: false) - render json: {notifications: notifications.aggregated_by_kind_and_subject} - else - render json: {errors: notifications.map(&:errors).compact}, status: :unprocessable_entity - end - end + if notifications.update_all(unread: false) + render json: {notifications: notifications.aggregated_by_kind_and_subject} + else + render json: {errors: notifications.map(&:errors).compact}, status: :unprocessable_entity + end + end - def destroy - notifications = Notification.where(notification_params) + def destroy + notifications = Notification.where(notification_params) - authorize_collection :destroy, notifications + authorize_collection :destroy, notifications - if notifications.destroy - head :no_content - else - render json: {errors: notifications.map(&:errors).compact}, status: :unprocessable_entity - end - end + if notifications.destroy + head :no_content + else + render json: {errors: notifications.map(&:errors).compact}, status: :unprocessable_entity + end + end - private + private - def notification_params - parameters = params.permit(:notificateable_id, :notificateable_type) + def notification_params + parameters = params.permit(:notificateable_id, :notificateable_type) - parameters[:notificateable_type] = parameters[:notificateable_type].titleize - parameters[:encrypted_notify_user_id] = current_user.encrypted_id + parameters[:notificateable_type] = parameters[:notificateable_type].titleize + parameters[:encrypted_notify_user_id] = current_user.encrypted_id - parameters - end + parameters + end - def authorize_collection(name, collection) - collection.each { |element| authorize! name, element } + def authorize_collection(name, collection) + collection.each { |element| authorize! name, element } + end + end end end diff --git a/backend/app/controllers/api/v1/omniauth_callbacks_controller.rb b/backend/app/controllers/api/v1/omniauth_callbacks_controller.rb index 61fd73095..8948e56cb 100644 --- a/backend/app/controllers/api/v1/omniauth_callbacks_controller.rb +++ b/backend/app/controllers/api/v1/omniauth_callbacks_controller.rb @@ -1,31 +1,35 @@ -class Api::V1::OmniauthCallbacksController < Devise::OmniauthCallbacksController - Devise.omniauth_providers.each do |provider| - define_method provider do - handle_omniauth - end - end +module Api + module V1 + class OmniauthCallbacksController < Devise::OmniauthCallbacksController + Devise.omniauth_providers.each do |provider| + define_method provider do + handle_omniauth + end + end - def failure - Rails.logger.warn("Api::V1::OmniauthCallbacksController#failure: #{failure_message}".yellow) - render json: {errors: failure_message}, status: 401 - end + def failure + Rails.logger.warn("Api::V1::OmniauthCallbacksController#failure: #{failure_message}".yellow) + render json: {errors: failure_message}, status: 401 + end - private + private - def handle_omniauth - user = User.find_for_database_authentication(email: email_param) - if user && user.invitation_token.nil? - render json: user, root: false, serializer: SessionSerializer - else - render json: {errors: "User not found"}, status: 401 - end - end + def handle_omniauth + user = User.find_for_database_authentication(email: email_param) + if user && user.invitation_token.nil? + render json: user, root: false, serializer: SessionSerializer + else + render json: {errors: "User not found"}, status: 401 + end + end - def oauth_params - @oauth_params ||= ActionController::Parameters.new(request.env["omniauth.auth"]) - end + def oauth_params + @oauth_params ||= ActionController::Parameters.new(request.env["omniauth.auth"]) + end - def email_param - oauth_params.fetch(:info).fetch(:email) + def email_param + oauth_params.fetch(:info).fetch(:email) + end + end end end diff --git a/backend/app/controllers/api/v1/oracle_requests_controller.rb b/backend/app/controllers/api/v1/oracle_requests_controller.rb index 121cbbf87..492b1bd79 100644 --- a/backend/app/controllers/api/v1/oracle_requests_controller.rb +++ b/backend/app/controllers/api/v1/oracle_requests_controller.rb @@ -1,56 +1,60 @@ -class Api::V1::OracleRequestsController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class OracleRequestsController < ApplicationController + skip_before_action :authenticate_user! - serialization_scope :oracle_token + serialization_scope :oracle_token - load_resource + load_resource - def show - render json: @oracle_request - end + def show + render json: @oracle_request + end - def create - if oracle_token.present? - @oracle_request.token = oracle_token - else - loop do - @oracle_request.token = SecureRandom.uuid + def create + if oracle_token.present? + @oracle_request.token = oracle_token + else + loop do + @oracle_request.token = SecureRandom.uuid - break unless OracleRequest.where(token: @oracle_request.token).exists? - end - end + break unless OracleRequest.where(token: @oracle_request.token).exists? + end + end - @oracle_request.save + @oracle_request.save - render json: @oracle_request, serializer: OracleRequestWithTokenSerializer - end + render json: @oracle_request, serializer: OracleRequestWithTokenSerializer + end - def update - if @oracle_request.can_edit?(oracle_token) - @oracle_request.update!(create_params) + def update + if @oracle_request.can_edit?(oracle_token) + @oracle_request.update!(create_params) - render json: @oracle_request - else - render json: {errors: "Unauthorized"}, status: :unauthorised - end - end + render json: @oracle_request + else + render json: {errors: "Unauthorized"}, status: :unauthorised + end + end - private - - def create_params - params.require(:oracle_request).permit( - :age, - :sex_id, - responce: [ - :name, - :confidence, - :correction - ], - symptom_ids: [] - ) - end + private + + def create_params + params.require(:oracle_request).permit( + :age, + :sex_id, + responce: [ + :name, + :confidence, + :correction + ], + symptom_ids: [] + ) + end - def oracle_token - request.headers["X-Oracle-Token"] + def oracle_token + request.headers["X-Oracle-Token"] + end + end end end diff --git a/backend/app/controllers/api/v1/passwords_controller.rb b/backend/app/controllers/api/v1/passwords_controller.rb index 3d9997980..6c0ef3fc6 100644 --- a/backend/app/controllers/api/v1/passwords_controller.rb +++ b/backend/app/controllers/api/v1/passwords_controller.rb @@ -1,52 +1,56 @@ -class Api::V1::PasswordsController < ApplicationController - skip_before_action :authenticate_user! - - def show - user = user_signed_in? ? current_user : User.with_reset_password_token(params[:id]) - - if user.blank? - raise ActiveRecord::RecordNotFound, "User not found" - else - render json: user, token: params[:id], serializer: PasswordSerializer - end - end - - def create - user = User.find_by!(email: email_param.downcase) +module Api + module V1 + class PasswordsController < ApplicationController + skip_before_action :authenticate_user! + + def show + user = user_signed_in? ? current_user : User.with_reset_password_token(params[:id]) + + if user.blank? + raise ActiveRecord::RecordNotFound, "User not found" + else + render json: user, token: params[:id], serializer: PasswordSerializer + end + end - return unless user.send_reset_password_instructions + def create + user = User.find_by!(email: email_param.downcase) - render json: user, serializer: PasswordSerializer - end + return unless user.send_reset_password_instructions - def update - if user_signed_in? - if current_user.update_with_password(update_password_params) - render json: current_user, token: params[:id], serializer: PasswordSerializer - else - render json: {errors: current_user.errors}, status: :unprocessable_entity + render json: user, serializer: PasswordSerializer end - else - user = User.reset_password_by_token(update_password_by_token_params) - if user.errors.empty? - render json: user, token: params[:id], serializer: PasswordSerializer - else - render json: {errors: user.errors}, status: :unprocessable_entity + + def update + if user_signed_in? + if current_user.update_with_password(update_password_params) + render json: current_user, token: params[:id], serializer: PasswordSerializer + else + render json: {errors: current_user.errors}, status: :unprocessable_entity + end + else + user = User.reset_password_by_token(update_password_by_token_params) + if user.errors.empty? + render json: user, token: params[:id], serializer: PasswordSerializer + else + render json: {errors: user.errors}, status: :unprocessable_entity + end + end end - end - end - private + private - def email_param - params.require(:password).fetch(:email) - end + def email_param + params.require(:password).fetch(:email) + end - def update_password_params - params.require(:password).permit(:current_password, :password, :password_confirmation) - end + def update_password_params + params.require(:password).permit(:current_password, :password, :password_confirmation) + end - def update_password_by_token_params - params.require(:password).permit(:reset_password_token, :password, :password_confirmation) + def update_password_by_token_params + params.require(:password).permit(:reset_password_token, :password, :password_confirmation) + end + end end end diff --git a/backend/app/controllers/api/v1/patterns_controller.rb b/backend/app/controllers/api/v1/patterns_controller.rb index 8ea2caee3..6fef47d25 100644 --- a/backend/app/controllers/api/v1/patterns_controller.rb +++ b/backend/app/controllers/api/v1/patterns_controller.rb @@ -1,64 +1,68 @@ -class Api::V1::PatternsController < ApplicationController - load_and_authorize_resource - skip_before_action :authenticate_user!, only: [:index] - - def index - page = params[:page] || 1 - pattern_ids = params[:pattern_ids] - - @patterns = - if pattern_ids.present? - Pattern.where(id: {"$in" => pattern_ids}) - else - Pattern.accessible_by(current_ability).where(encrypted_user_id: encrypted_user_id) +module Api + module V1 + class PatternsController < ApplicationController + load_and_authorize_resource + skip_before_action :authenticate_user!, only: [:index] + + def index + page = params[:page] || 1 + pattern_ids = params[:pattern_ids] + + @patterns = + if pattern_ids.present? + Pattern.where(id: {"$in" => pattern_ids}) + else + Pattern.accessible_by(current_ability).where(encrypted_user_id: encrypted_user_id) + end + + render json: @patterns.page(page).per(10) end - render json: @patterns.page(page).per(10) - end - - def show - pattern = Pattern.find_by(id: pattern_params[:id]) + def show + pattern = Pattern.find_by(id: pattern_params[:id]) - render json: pattern - end + render json: pattern + end - def create - @pattern = PatternCreator.new(pattern_params).create + def create + @pattern = PatternCreator.new(pattern_params).create - render json: @pattern - end + render json: @pattern + end - def update - @pattern.update(pattern_params) + def update + @pattern.update(pattern_params) - render json: @pattern - end + render json: @pattern + end - def destroy - pattern = Pattern.find_by(id: params[:id]) + def destroy + pattern = Pattern.find_by(id: params[:id]) - authorize! :destroy, pattern + authorize! :destroy, pattern - if pattern.destroy - head :no_content - else - render json: {errors: pattern.errors}, status: :unprocessable_entity - end - end + if pattern.destroy + head :no_content + else + render json: {errors: pattern.errors}, status: :unprocessable_entity + end + end - private + private - def pattern_params - params.require(:pattern) - .permit(:name, :start_at, :end_at, includes: [:id, :category, :label]) - .merge(user_id: current_user.id) - end + def pattern_params + params.require(:pattern) + .permit(:name, :start_at, :end_at, includes: [:id, :category, :label]) + .merge(user_id: current_user.id) + end - def current_ability - @current_ability ||= Ability.new(current_user) - end + def current_ability + @current_ability ||= Ability.new(current_user) + end - def encrypted_user_id - @encrypted_user_id ||= SymmetricEncryption.encrypt(current_user.id) + def encrypted_user_id + @encrypted_user_id ||= SymmetricEncryption.encrypt(current_user.id) + end + end end end diff --git a/backend/app/controllers/api/v1/postables_controller.rb b/backend/app/controllers/api/v1/postables_controller.rb index 115f231a9..b876cef7c 100644 --- a/backend/app/controllers/api/v1/postables_controller.rb +++ b/backend/app/controllers/api/v1/postables_controller.rb @@ -1,14 +1,18 @@ -class Api::V1::PostablesController < ApplicationController - load_and_authorize_resource +module Api + module V1 + class PostablesController < ApplicationController + load_and_authorize_resource - def index - render json: PostableSerializer.new( - @postables - .where(encrypted_user_id: current_user.encrypted_id) - .order_by(created_at: :desc) - .page(params[:page]) - .per(20), - current_user - ) + def index + render json: PostableSerializer.new( + @postables + .where(encrypted_user_id: current_user.encrypted_id) + .order_by(created_at: :desc) + .page(params[:page]) + .per(20), + current_user + ) + end + end end end diff --git a/backend/app/controllers/api/v1/posts_controller.rb b/backend/app/controllers/api/v1/posts_controller.rb index 2a070bfc6..d323a80fb 100644 --- a/backend/app/controllers/api/v1/posts_controller.rb +++ b/backend/app/controllers/api/v1/posts_controller.rb @@ -1,42 +1,46 @@ -class Api::V1::PostsController < ApplicationController - load_and_authorize_resource - skip_before_action :authenticate_user!, only: [:index, :show] +module Api + module V1 + class PostsController < ApplicationController + load_and_authorize_resource + skip_before_action :authenticate_user!, only: [:index, :show] - def index - if params[:summary] - render json: SummaryPosts.new(current_user).show_list - else - @posts = DiscussionPosts.new(params, current_user).show_list + def index + if params[:summary] + render json: SummaryPosts.new(current_user).show_list + else + @posts = DiscussionPosts.new(params, current_user).show_list - results = @posts - .includes([:comments, :notifications, :reactions]) - .order(last_commented: :desc, created_at: :desc) - .page(params[:page]) - .per(10) - render json: results - end - end + results = @posts + .includes([:comments, :notifications, :reactions]) + .order(last_commented: :desc, created_at: :desc) + .page(params[:page]) + .per(10) + render json: results + end + end - def show - render json: @post - end + def show + render json: @post + end - def create - @post.encrypted_user_id = current_user.encrypted_id + def create + @post.encrypted_user_id = current_user.encrypted_id - if @post.save - render json: @post, status: :created - else - render json: {errors: @post.errors}, status: :unprocessable_entity - end - end + if @post.save + render json: @post, status: :created + else + render json: {errors: @post.errors}, status: :unprocessable_entity + end + end - private + private - def create_params - params.require(:post).permit( - :title, :body, - tag_ids: [], symptom_ids: [], condition_ids: [], treatment_ids: [] - ) + def create_params + params.require(:post).permit( + :title, :body, + tag_ids: [], symptom_ids: [], condition_ids: [], treatment_ids: [] + ) + end + end end end diff --git a/backend/app/controllers/api/v1/profiles_controller.rb b/backend/app/controllers/api/v1/profiles_controller.rb index d4c7186e1..5d8ba86a7 100644 --- a/backend/app/controllers/api/v1/profiles_controller.rb +++ b/backend/app/controllers/api/v1/profiles_controller.rb @@ -1,71 +1,75 @@ -class Api::V1::ProfilesController < ApplicationController - require "sidekiq/api" +module Api + module V1 + class ProfilesController < ApplicationController + require "sidekiq/api" - load_and_authorize_resource - skip_before_action :authenticate_user!, only: [:index] + load_and_authorize_resource + skip_before_action :authenticate_user!, only: [:index] - def index - post = Post.find(params[:post_id]) + def index + post = Post.find(params[:post_id]) - encrypted_user_ids = - (post.comments.distinct(:encrypted_user_id) << post.encrypted_user_id).uniq.map do |encrypted_id| - SymmetricEncryption.decrypt(encrypted_id) - end + encrypted_user_ids = + (post.comments.distinct(:encrypted_user_id) << post.encrypted_user_id).uniq.map do |encrypted_id| + SymmetricEncryption.decrypt(encrypted_id) + end - @profiles = Profile.where(user_id: encrypted_user_ids).where.not(slug_name: nil) - render json: @profiles.map { |profile| profile.attributes.slice("screen_name", "slug_name") } - end + @profiles = Profile.where(user_id: encrypted_user_ids).where.not(slug_name: nil) + render json: @profiles.map { |profile| profile.attributes.slice("screen_name", "slug_name") } + end - def show - render json: @profile - end + def show + render json: @profile + end - def update - initial_onboarding_reminder = params.dig(:profile, :onboarding_reminder) + def update + initial_onboarding_reminder = params.dig(:profile, :onboarding_reminder) - @profile.assign_attributes(update_params.merge(transform_hash_time)) - time_changed = @profile.checkin_reminder_at_changed? || @profile.time_zone_name_changed? - @profile.save! + @profile.assign_attributes(update_params.merge(transform_hash_time)) + time_changed = @profile.checkin_reminder_at_changed? || @profile.time_zone_name_changed? + @profile.save! - if time_changed || initial_onboarding_reminder - delete_old_job(@profile.reminder_job_id) + if time_changed || initial_onboarding_reminder + delete_old_job(@profile.reminder_job_id) - job_id = CheckinReminderJob.perform_in(get_reminder_time.minutes, @profile.id, @profile.checkin_reminder_at) - @profile.update_column(:reminder_job_id, job_id) - end + job_id = CheckinReminderJob.perform_in(get_reminder_time.minutes, @profile.id, @profile.checkin_reminder_at) + @profile.update_column(:reminder_job_id, job_id) + end - current_user.profile.reload - set_locale - render json: @profile - end + current_user.profile.reload + set_locale + render json: @profile + end - private + private - def update_params - params.require(:profile).permit( - :country_id, :sex_id, :onboarding_step_id, :birth_date, - :day_habit_id, :education_level_id, :day_walking_hours, - :pressure_units, :temperature_units, :screen_name, :notify, - :checkin_reminder, :time_zone_name, :notify_top_posts, ethnicity_ids: [] - ) - end + def update_params + params.require(:profile).permit( + :country_id, :sex_id, :onboarding_step_id, :birth_date, + :day_habit_id, :education_level_id, :day_walking_hours, + :pressure_units, :temperature_units, :screen_name, :notify, + :checkin_reminder, :time_zone_name, :notify_top_posts, ethnicity_ids: [] + ) + end - def transform_hash_time - checkin_reminder_at = params.require(:profile)[:checkin_reminder_at] - user_time = checkin_reminder_at && checkin_reminder_at.values.join(":") + def transform_hash_time + checkin_reminder_at = params.require(:profile)[:checkin_reminder_at] + user_time = checkin_reminder_at && checkin_reminder_at.values.join(":") - {checkin_reminder_at: user_time.try(:to_time, :utc)} - end + {checkin_reminder_at: user_time.try(:to_time, :utc)} + end - def get_reminder_time - time_zone_name = @profile.time_zone_name - checkin_at_timezone = @profile.checkin_reminder_at.strftime("%H:%M").in_time_zone(time_zone_name) + def get_reminder_time + time_zone_name = @profile.time_zone_name + checkin_at_timezone = @profile.checkin_reminder_at.strftime("%H:%M").in_time_zone(time_zone_name) - # Select minutes - (checkin_at_timezone - Time.current.in_time_zone(time_zone_name)).divmod(1.day)[1].divmod(1.minute)[0] - end + # Select minutes + (checkin_at_timezone - Time.current.in_time_zone(time_zone_name)).divmod(1.day)[1].divmod(1.minute)[0] + end - def delete_old_job(enqueued_job_id) - Sidekiq::ScheduledSet.new.find_job(enqueued_job_id)&.delete + def delete_old_job(enqueued_job_id) + Sidekiq::ScheduledSet.new.find_job(enqueued_job_id)&.delete + end + end end end diff --git a/backend/app/controllers/api/v1/promotion_rates_controller.rb b/backend/app/controllers/api/v1/promotion_rates_controller.rb index 039c71618..a9c874706 100644 --- a/backend/app/controllers/api/v1/promotion_rates_controller.rb +++ b/backend/app/controllers/api/v1/promotion_rates_controller.rb @@ -1,31 +1,35 @@ -class Api::V1::PromotionRatesController < ApplicationController - load_and_authorize_resource +module Api + module V1 + class PromotionRatesController < ApplicationController + load_and_authorize_resource - def show - render json: @promotion_rate - end + def show + render json: @promotion_rate + end - def create - @promotion_rate.save + def create + @promotion_rate.save - render json: @promotion_rate - end + render json: @promotion_rate + end - def update - @promotion_rate.update(resource_params.merge(additional_params)) + def update + @promotion_rate.update(resource_params.merge(additional_params)) - render json: @promotion_rate - end + render json: @promotion_rate + end - private + private - def resource_params - params.require(:promotion_rate).permit(:checkin_id, :score, :feedback) - end + def resource_params + params.require(:promotion_rate).permit(:checkin_id, :score, :feedback) + end - def additional_params - user = @promotion_rate.checkin.user + def additional_params + user = @promotion_rate.checkin.user - {user_created_at: user.created_at} + {user_created_at: user.created_at} + end + end end end diff --git a/backend/app/controllers/api/v1/pushers_controller.rb b/backend/app/controllers/api/v1/pushers_controller.rb index bfaa08dbf..a1356172b 100644 --- a/backend/app/controllers/api/v1/pushers_controller.rb +++ b/backend/app/controllers/api/v1/pushers_controller.rb @@ -1,13 +1,17 @@ -class Api::V1::PushersController < ApplicationController - def create - render json: Flaredown.pusher.authenticate!(current_user, socket_id) - rescue - render json: {errors: "Bad authentication"}, status: "403" - end +module Api + module V1 + class PushersController < ApplicationController + def create + render json: Flaredown.pusher.authenticate!(current_user, socket_id) + rescue + render json: {errors: "Bad authentication"}, status: "403" + end - private + private - def socket_id - params.require(:socket_id) + def socket_id + params.require(:socket_id) + end + end end end diff --git a/backend/app/controllers/api/v1/reactions_controller.rb b/backend/app/controllers/api/v1/reactions_controller.rb index bcabdfd13..b7bf42f77 100644 --- a/backend/app/controllers/api/v1/reactions_controller.rb +++ b/backend/app/controllers/api/v1/reactions_controller.rb @@ -1,73 +1,77 @@ -class Api::V1::ReactionsController < ApplicationController - def create - react(__method__) - end +module Api + module V1 + class ReactionsController < ApplicationController + def create + react(__method__) + end - def update - react(__method__) - end + def update + react(__method__) + end - def destroy - reaction = Reaction.where(reaction_params).first + def destroy + reaction = Reaction.where(reaction_params).first - authorize! :destroy, reaction + authorize! :destroy, reaction - if reaction.destroy - UpdatePostCountersJob.perform_async(parent_id: reaction_params[:reactable_id], - parent_type: reaction_params[:reactable_type]) + if reaction.destroy + UpdatePostCountersJob.perform_async(parent_id: reaction_params[:reactable_id], + parent_type: reaction_params[:reactable_type]) - head :no_content - else - render json: {errors: reaction.errors}, status: :unprocessable_entity - end - end + head :no_content + else + render json: {errors: reaction.errors}, status: :unprocessable_entity + end + end - private + private - def react(method_name) - reaction = Reaction.find_or_initialize_by(reaction_params) + def react(method_name) + reaction = Reaction.find_or_initialize_by(reaction_params) - authorize! method_name, reaction + authorize! method_name, reaction - if reaction.save - UpdatePostCountersJob.perform_async(parent_id: reaction_params[:reactable_id], - parent_type: reaction_params[:reactable_type]) + if reaction.save + UpdatePostCountersJob.perform_async(parent_id: reaction_params[:reactable_id], + parent_type: reaction_params[:reactable_type]) - unless reaction.encrypted_user_id == reaction.reactable.encrypted_user_id - Notification.create( - kind: :reaction, - notificateable: reaction.reactable, - encrypted_user_id: reaction.encrypted_user_id, - encrypted_notify_user_id: reaction.reactable.encrypted_user_id - ) - end + unless reaction.encrypted_user_id == reaction.reactable.encrypted_user_id + Notification.create( + kind: :reaction, + notificateable: reaction.reactable, + encrypted_user_id: reaction.encrypted_user_id, + encrypted_notify_user_id: reaction.reactable.encrypted_user_id + ) + end - reaction.id = params[:id] if params[:id].present? + reaction.id = params[:id] if params[:id].present? - render json: serialized_reaction(reaction), status: :created - else - render json: {errors: reaction.errors}, status: :unprocessable_entity - end - end + render json: serialized_reaction(reaction), status: :created + else + render json: {errors: reaction.errors}, status: :unprocessable_entity + end + end - def reaction_params - reaction = params.require(:reaction) + def reaction_params + reaction = params.require(:reaction) - { - value: reaction[:value], - reactable_id: reaction[:reactable_id], - reactable_type: reaction[:reactable_type].titleize, - encrypted_user_id: current_user.encrypted_id - } - end + { + value: reaction[:value], + reactable_id: reaction[:reactable_id], + reactable_type: reaction[:reactable_type].titleize, + encrypted_user_id: current_user.encrypted_id + } + end - def serialized_reaction(reaction) - ReactionSerializer - .new( - Reaction.similar_to(reaction).values_count_with_participated(current_user.encrypted_id), - reaction.reactable_id.to_s, - reaction.reactable_type - ) - .serialize_one + def serialized_reaction(reaction) + ReactionSerializer + .new( + Reaction.similar_to(reaction).values_count_with_participated(current_user.encrypted_id), + reaction.reactable_id.to_s, + reaction.reactable_type + ) + .serialize_one + end + end end end diff --git a/backend/app/controllers/api/v1/registrations_controller.rb b/backend/app/controllers/api/v1/registrations_controller.rb index 5fcba2298..aba7761a3 100644 --- a/backend/app/controllers/api/v1/registrations_controller.rb +++ b/backend/app/controllers/api/v1/registrations_controller.rb @@ -1,11 +1,15 @@ -class Api::V1::RegistrationsController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class RegistrationsController < ApplicationController + skip_before_action :authenticate_user! - def create - render json: Registration.create!(params) - end + def create + render json: Registration.create!(params) + end - def destroy - render json: Registration.delete!(params) + def destroy + render json: Registration.delete!(params) + end + end end end diff --git a/backend/app/controllers/api/v1/searches_controller.rb b/backend/app/controllers/api/v1/searches_controller.rb index b4c5f990f..33a2954c4 100644 --- a/backend/app/controllers/api/v1/searches_controller.rb +++ b/backend/app/controllers/api/v1/searches_controller.rb @@ -1,30 +1,34 @@ -class Api::V1::SearchesController < ApplicationController - SEARCH_MAPPER = { - "dose" => Search::ForDose, - "food" => Search::ForFood, - "topic" => Search::ForTopic - }.freeze +module Api + module V1 + class SearchesController < ApplicationController + SEARCH_MAPPER = { + "dose" => Search::ForDose, + "food" => Search::ForFood, + "topic" => Search::ForTopic + }.freeze - skip_before_action :authenticate_user!, only: :show + skip_before_action :authenticate_user!, only: :show - def show - search = (SEARCH_MAPPER[resource_param] || Search).new(search_params) + def show + search = (SEARCH_MAPPER[resource_param] || Search).new(search_params) - # FIXME - # rubocop:disable Style/SignalException - fail(ActiveRecord::RecordInvalid, search) if search.invalid? - # rubocop:enable Style/SignalException + # FIXME + # rubocop:disable Style/SignalException + fail(ActiveRecord::RecordInvalid, search) if search.invalid? + # rubocop:enable Style/SignalException - render json: search, serializer: SearchSerializer - end + render json: search, serializer: SearchSerializer + end - def search_params - params.permit(:resource, :scope, query: [:name, :treatment_id]).tap do |params| - params[:user] = current_user - end - end + def search_params + params.permit(:resource, :scope, query: [:name, :treatment_id]).tap do |params| + params[:user] = current_user + end + end - def resource_param - params[:resource] + def resource_param + params[:resource] + end + end end end diff --git a/backend/app/controllers/api/v1/sessions_controller.rb b/backend/app/controllers/api/v1/sessions_controller.rb index f31562445..e41f30647 100644 --- a/backend/app/controllers/api/v1/sessions_controller.rb +++ b/backend/app/controllers/api/v1/sessions_controller.rb @@ -1,25 +1,29 @@ -class Api::V1::SessionsController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class SessionsController < ApplicationController + skip_before_action :authenticate_user! - def create - # FIXME - # rubocop:disable Style/SignalException - fail "missing information" if params[:user].nil? - fail "invalid email or password" if user.nil? - # rubocop:enable Style/SignalException + def create + # FIXME + # rubocop:disable Style/SignalException + fail "missing information" if params[:user].nil? + fail "invalid email or password" if user.nil? + # rubocop:enable Style/SignalException - render json: user, root: false, serializer: SessionSerializer - rescue => e - render json: {errors: Array(e.message)}, status: 401 - end + render json: user, root: false, serializer: SessionSerializer + rescue => e + render json: {errors: Array(e.message)}, status: 401 + end - private + private - def user - @user ||= - begin - user = User.find_for_database_authentication(email: params[:user][:email]) - user if user && user.valid_password?(params[:user][:password]) + def user + @user ||= + begin + user = User.find_for_database_authentication(email: params[:user][:email]) + user if user && user.valid_password?(params[:user][:password]) + end end + end end end diff --git a/backend/app/controllers/api/v1/sexes_controller.rb b/backend/app/controllers/api/v1/sexes_controller.rb index 41913ea39..7efe4c138 100644 --- a/backend/app/controllers/api/v1/sexes_controller.rb +++ b/backend/app/controllers/api/v1/sexes_controller.rb @@ -1,23 +1,27 @@ -class Api::V1::SexesController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class SexesController < ApplicationController + skip_before_action :authenticate_user! - def index - render json: Sex.all - end + def index + render json: Sex.all + end - def show - sex = Sex.find(sex_id) - render json: sex - end + def show + sex = Sex.find(sex_id) + render json: sex + end - private + private - def sex_id - id = params.require(:id) - # FIXME - # rubocop:disable Style/SignalException - fail(ActionController::BadRequest, "id param is not a valid sex id") unless Sex.all_ids.include?(id) - # rubocop:enable Style/SignalException - id + def sex_id + id = params.require(:id) + # FIXME + # rubocop:disable Style/SignalException + fail(ActionController::BadRequest, "id param is not a valid sex id") unless Sex.all_ids.include?(id) + # rubocop:enable Style/SignalException + id + end + end end end diff --git a/backend/app/controllers/api/v1/symptoms_controller.rb b/backend/app/controllers/api/v1/symptoms_controller.rb index 07f4af03c..c4bdc43e7 100644 --- a/backend/app/controllers/api/v1/symptoms_controller.rb +++ b/backend/app/controllers/api/v1/symptoms_controller.rb @@ -1,29 +1,33 @@ -class Api::V1::SymptomsController < ApplicationController - load_and_authorize_resource - skip_before_action :authenticate_user!, only: [:show] +module Api + module V1 + class SymptomsController < ApplicationController + load_and_authorize_resource + skip_before_action :authenticate_user!, only: [:show] - def index - @symptoms = @symptoms.includes(:translations) - @symptoms = ids.present? ? @symptoms.where(id: ids) : @symptoms.order(:name).limit(50) + def index + @symptoms = @symptoms.includes(:translations) + @symptoms = ids.present? ? @symptoms.where(id: ids) : @symptoms.order(:name).limit(50) - render json: @symptoms - end + render json: @symptoms + end - def show - render json: @symptom - end + def show + render json: @symptom + end - def create - render json: TrackableCreator.new(@symptom, current_user).create! - end + def create + render json: TrackableCreator.new(@symptom, current_user).create! + end - private + private - def create_params - params.require(:symptom).permit(:name) - end + def create_params + params.require(:symptom).permit(:name) + end - def ids - @ids ||= params[:ids] if params[:ids].is_a?(Array) + def ids + @ids ||= params[:ids] if params[:ids].is_a?(Array) + end + end end end diff --git a/backend/app/controllers/api/v1/tags_controller.rb b/backend/app/controllers/api/v1/tags_controller.rb index d04a30f09..cc32c4d76 100644 --- a/backend/app/controllers/api/v1/tags_controller.rb +++ b/backend/app/controllers/api/v1/tags_controller.rb @@ -1,36 +1,40 @@ -class Api::V1::TagsController < ApplicationController - load_and_authorize_resource - skip_before_action :authenticate_user!, only: [:show] +module Api + module V1 + class TagsController < ApplicationController + load_and_authorize_resource + skip_before_action :authenticate_user!, only: [:show] - def index - @tags = @tags.includes(:translations) - if ids.present? - @tags = @tags.where(id: ids) - elsif scope.present? - @tags = CollectionRetriever.new(Tag, scope, current_user).retrieve - end - render json: @tags - end + def index + @tags = @tags.includes(:translations) + if ids.present? + @tags = @tags.where(id: ids) + elsif scope.present? + @tags = CollectionRetriever.new(Tag, scope, current_user).retrieve + end + render json: @tags + end - def show - render json: @tag - end + def show + render json: @tag + end - def create - render json: TrackableCreator.new(@tag, current_user).create! - end + def create + render json: TrackableCreator.new(@tag, current_user).create! + end - private + private - def create_params - params.require(:tag).permit(:name) - end + def create_params + params.require(:tag).permit(:name) + end - def ids - @ids ||= params[:ids] - end + def ids + @ids ||= params[:ids] + end - def scope - @scope ||= params[:scope].try(:to_sym) + def scope + @scope ||= params[:scope].try(:to_sym) + end + end end end diff --git a/backend/app/controllers/api/v1/topic_followings_controller.rb b/backend/app/controllers/api/v1/topic_followings_controller.rb index 5691deaa7..609d506b0 100644 --- a/backend/app/controllers/api/v1/topic_followings_controller.rb +++ b/backend/app/controllers/api/v1/topic_followings_controller.rb @@ -1,28 +1,32 @@ -class Api::V1::TopicFollowingsController < ApplicationController - load_and_authorize_resource +module Api + module V1 + class TopicFollowingsController < ApplicationController + load_and_authorize_resource - def show - render json: @topic_following - end + def show + render json: @topic_following + end - def update - if @topic_following.update(update_params) - render json: @topic_following, status: :ok - else - render json: {errors: @topic_following.errors}, status: :unprocessable_entity - end - end + def update + if @topic_following.update(update_params) + render json: @topic_following, status: :ok + else + render json: {errors: @topic_following.errors}, status: :unprocessable_entity + end + end - private + private - def update_params - empty_params = { - "tag_ids" => [], - "symptom_ids" => [], - "condition_ids" => [], - "treatment_ids" => [] - } + def update_params + empty_params = { + "tag_ids" => [], + "symptom_ids" => [], + "condition_ids" => [], + "treatment_ids" => [] + } - empty_params.merge(params.require(:topic_following).permit(empty_params)) + empty_params.merge(params.require(:topic_following).permit(empty_params)) + end + end end end diff --git a/backend/app/controllers/api/v1/trackings_controller.rb b/backend/app/controllers/api/v1/trackings_controller.rb index 0f89ee173..d0ae4c65c 100644 --- a/backend/app/controllers/api/v1/trackings_controller.rb +++ b/backend/app/controllers/api/v1/trackings_controller.rb @@ -1,42 +1,46 @@ -class Api::V1::TrackingsController < ApplicationController - load_and_authorize_resource except: :create +module Api + module V1 + class TrackingsController < ApplicationController + load_and_authorize_resource except: :create - def index - render json: @trackings.by_trackable_type(trackable_type).active_at(at) - end + def index + render json: @trackings.by_trackable_type(trackable_type).active_at(at) + end - def show - render json: @tracking - end + def show + render json: @tracking + end - def create - tracking = Tracking.new(create_params.merge(start_at: Time.zone.today, user: current_user)) + def create + tracking = Tracking.new(create_params.merge(start_at: Time.zone.today, user: current_user)) - authorize! :create, tracking + authorize! :create, tracking - tracking.save! + tracking.save! - current_user.topic_following.add_topic("#{tracking.trackable_type.downcase}_ids", tracking.trackable_id) + current_user.topic_following.add_topic("#{tracking.trackable_type.downcase}_ids", tracking.trackable_id) - render json: tracking - end + render json: tracking + end - def destroy - TrackingDestroyer.new(current_user, @tracking, Time.zone.today).destroy - head :no_content - end + def destroy + TrackingDestroyer.new(current_user, @tracking, Time.zone.today).destroy + head :no_content + end - private + private - def at - Time.zone.parse(params.require(:at)) - end + def at + Time.zone.parse(params.require(:at)) + end - def trackable_type - params.require(:trackable_type) - end + def trackable_type + params.require(:trackable_type) + end - def create_params - params.require(:tracking).permit(:trackable_id, :trackable_type, :color_id) + def create_params + params.require(:tracking).permit(:trackable_id, :trackable_type, :color_id) + end + end end end diff --git a/backend/app/controllers/api/v1/treatments_controller.rb b/backend/app/controllers/api/v1/treatments_controller.rb index 45dce99e9..b13c3caf9 100644 --- a/backend/app/controllers/api/v1/treatments_controller.rb +++ b/backend/app/controllers/api/v1/treatments_controller.rb @@ -1,29 +1,33 @@ -class Api::V1::TreatmentsController < ApplicationController - load_and_authorize_resource - skip_before_action :authenticate_user!, only: [:show] +module Api + module V1 + class TreatmentsController < ApplicationController + load_and_authorize_resource + skip_before_action :authenticate_user!, only: [:show] - def index - @treatments = @treatments.includes(:translations) - @treatments = ids.present? ? @treatments.where(id: ids) : @treatments.order(:name).limit(50) + def index + @treatments = @treatments.includes(:translations) + @treatments = ids.present? ? @treatments.where(id: ids) : @treatments.order(:name).limit(50) - render json: @treatments - end + render json: @treatments + end - def show - render json: @treatment - end + def show + render json: @treatment + end - def create - render json: TrackableCreator.new(@treatment, current_user).create! - end + def create + render json: TrackableCreator.new(@treatment, current_user).create! + end - private + private - def create_params - params.require(:treatment).permit(:name) - end + def create_params + params.require(:treatment).permit(:name) + end - def ids - @ids ||= params[:ids] if params[:ids].is_a?(Array) + def ids + @ids ||= params[:ids] if params[:ids].is_a?(Array) + end + end end end diff --git a/backend/app/controllers/api/v1/unsubscribes_controller.rb b/backend/app/controllers/api/v1/unsubscribes_controller.rb index 4c23d89e4..04cf0ddfb 100644 --- a/backend/app/controllers/api/v1/unsubscribes_controller.rb +++ b/backend/app/controllers/api/v1/unsubscribes_controller.rb @@ -1,26 +1,30 @@ -class Api::V1::UnsubscribesController < ApplicationController - skip_before_action :authenticate_user! +module Api + module V1 + class UnsubscribesController < ApplicationController + skip_before_action :authenticate_user! - def update - @profile = Profile.find_by(notify_token: activation_params[:notify_token]) - @profile&.update_column(attribute_dispatcher_key, false) + def update + @profile = Profile.find_by(notify_token: activation_params[:notify_token]) + @profile&.update_column(attribute_dispatcher_key, false) - render json: @profile - end + render json: @profile + end - private + private - def activation_params - params.permit(:notify_token, :notify_top_posts, :stop_remind) - end + def activation_params + params.permit(:notify_token, :notify_top_posts, :stop_remind) + end - def attribute_dispatcher_key - if activation_params[:stop_remind] - :checkin_reminder - elsif activation_params[:notify_top_posts] - :notify_top_posts - else - :notify + def attribute_dispatcher_key + if activation_params[:stop_remind] + :checkin_reminder + elsif activation_params[:notify_top_posts] + :notify_top_posts + else + :notify + end + end end end end diff --git a/backend/app/controllers/api/v1/users_controller.rb b/backend/app/controllers/api/v1/users_controller.rb index 0a5862549..380d22bff 100644 --- a/backend/app/controllers/api/v1/users_controller.rb +++ b/backend/app/controllers/api/v1/users_controller.rb @@ -1,19 +1,23 @@ -class Api::V1::UsersController < ApplicationController - load_and_authorize_resource +module Api + module V1 + class UsersController < ApplicationController + load_and_authorize_resource - def show - render json: @user - end + def show + render json: @user + end - def update - @user.update!(user_params) + def update + @user.update!(user_params) - render json: @user - end + render json: @user + end - private + private - def user_params - params.require(:user).permit(:email) + def user_params + params.require(:user).permit(:email) + end + end end end diff --git a/backend/app/controllers/api/v1/weathers_controller.rb b/backend/app/controllers/api/v1/weathers_controller.rb index 243183818..cff32fa0f 100644 --- a/backend/app/controllers/api/v1/weathers_controller.rb +++ b/backend/app/controllers/api/v1/weathers_controller.rb @@ -1,15 +1,19 @@ -class Api::V1::WeathersController < ApplicationController - def index - unless params[:postal_code].blank? - weather = WeatherRetriever.get(Date.parse(params.require(:date)), params.require(:postal_code)) - end +module Api + module V1 + class WeathersController < ApplicationController + def index + unless params[:postal_code].blank? + weather = WeatherRetriever.get(Date.parse(params.require(:date)), params.require(:postal_code)) + end - authorize! :read, weather + authorize! :read, weather - if weather.present? - render json: weather - else - render json: {weathers: []} + if weather.present? + render json: weather + else + render json: {weathers: []} + end + end end end end diff --git a/backend/spec/models/food_spec.rb b/backend/spec/models/food_spec.rb index 021488e68..84ea9d444 100644 --- a/backend/spec/models/food_spec.rb +++ b/backend/spec/models/food_spec.rb @@ -23,7 +23,7 @@ describe "fts" do it "return same global foods" do another_user = create(:user) - result = Food.send(:fts, query[:name], MAX_ROWS, another_user.id) + result = Food.fts(query[:name], MAX_ROWS, another_user.id) expect(result).to eq [global_food, same_food_1] expect(result.count).to eq MAX_ROWS @@ -32,7 +32,7 @@ end it "retrun local and global foods for author" do - expect(Food.send(:fts, query[:name], MAX_ROWS, user_food.user_id)).to eq [global_food, personal_food] + expect(Food.fts(query[:name], MAX_ROWS, user_food.user_id)).to eq [global_food, personal_food] end end end diff --git a/backend/spec/spec_helper.rb b/backend/spec/spec_helper.rb index 2b5fcf1af..e509d1539 100644 --- a/backend/spec/spec_helper.rb +++ b/backend/spec/spec_helper.rb @@ -25,6 +25,12 @@ config.before(:suite) do # TestEnv.init end + + # config.after(:each) do |example| + # if example.exception + # Pry.start(example) + # end + # end end ActiveRecord::Migration.maintain_test_schema! From 9023d61ad6d1c167a79e2f5c3ce9dc65d0a69259 Mon Sep 17 00:00:00 2001 From: Ben Langfeld Date: Thu, 14 Oct 2021 19:27:12 -0300 Subject: [PATCH 3/3] Back out some unrelated changes --- backend/spec/models/food_spec.rb | 4 ++-- backend/spec/spec_helper.rb | 6 ------ 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/backend/spec/models/food_spec.rb b/backend/spec/models/food_spec.rb index 84ea9d444..021488e68 100644 --- a/backend/spec/models/food_spec.rb +++ b/backend/spec/models/food_spec.rb @@ -23,7 +23,7 @@ describe "fts" do it "return same global foods" do another_user = create(:user) - result = Food.fts(query[:name], MAX_ROWS, another_user.id) + result = Food.send(:fts, query[:name], MAX_ROWS, another_user.id) expect(result).to eq [global_food, same_food_1] expect(result.count).to eq MAX_ROWS @@ -32,7 +32,7 @@ end it "retrun local and global foods for author" do - expect(Food.fts(query[:name], MAX_ROWS, user_food.user_id)).to eq [global_food, personal_food] + expect(Food.send(:fts, query[:name], MAX_ROWS, user_food.user_id)).to eq [global_food, personal_food] end end end diff --git a/backend/spec/spec_helper.rb b/backend/spec/spec_helper.rb index e509d1539..2b5fcf1af 100644 --- a/backend/spec/spec_helper.rb +++ b/backend/spec/spec_helper.rb @@ -25,12 +25,6 @@ config.before(:suite) do # TestEnv.init end - - # config.after(:each) do |example| - # if example.exception - # Pry.start(example) - # end - # end end ActiveRecord::Migration.maintain_test_schema!