레일에서 루비 메서드 리팩토링

션 마자르

내 레일 앱의 알림 모델에 다음 코드가 있습니다.

나는 그것을 조금 리팩토링하고 싶습니다. 확실히 잘못된 것은 "객체가 존재하는지 확인한 다음 그것으로 무언가를한다"부분입니다. 나는 사용할 수 있다고 생각 try하지만 정확히 어떻게 작동하는지 모르겠습니다. sby가 어떻게해야하는지 말해 줄 수 있나요 (그것 try보다 더 좋은 방법이 있다면)?

나머지 코드와 관련하여 다른 관찰이 있습니까?

#check and decrease chat notification that happens between 2 given users (since 1v1 chat notification number max limit is 1)
def self.decreasing_chat_notification_number(current_user, user)
  if self.between_chat_recipient(current_user, user).unchecked.any?
    notification = self.between_chat_recipient(current_user, user).unchecked.first
    checking_and_decreasing_notification(notification)
  end
end

#check and decrease all the task notifications that happens between 2 given users
def self.decreasing_task_notification_number(current_user, user)
  if self.task.between_other_recipient(current_user, user).unchecked
    self.task.between_other_recipient(current_user, user).unchecked.each do |notification|
      checking_and_decreasing_notification(notification)
    end
  end
end

#check and decrease all the post notifications that happened on a given post
def self.decreeasing_post_notification_number(current_user, post)
  if self.post.this_post_comments(current_user, post).unchecked
    self.post.this_post_comments(current_user, post).unchecked.each do |notification|
      checking_and_decreasing_notification(notification)
    end
  end
end

private

def check_notification #chat notification gets checked
  if self.checked_at == nil
    update_attributes(checked_at: Time.zone.now)
  end
end

def checking_and_decreasing_notification(notification)
  notification.check_notification
  current_user.decrease_new_other_notifications
  current_user.decreased_other_number_pusher
end

범위 :

scope :not_chat, -> { where.not(notifiable_type: "Message") }
scope :chat, -> { where(notifiable_type: "Message") }
scope :task, -> { where(notifiable_type: "Task") }
scope :post, -> { where(notifiable_type: "Post") }
scope :checked, -> { where.not(checked_at: nil) }
scope :unchecked, -> { where(checked_at: nil) }
scope :this_post_comments, -> (recipient_id, post_id) do
  where("notifications.recipient_id = ? AND notifications.notifiable_id = ?", recipient_id, post_id)
end
scope :between_chat_recipient, -> (recipient_id, sender_id) do
  where("notifications.recipient_id = ? AND notifications.sender_id = ? AND notifications.notifiable_type = ?", recipient_id, sender_id, "Message")
end
scope :between_other_recipient, -> (recipient_id, sender_id) do
  where("notifications.recipient_id = ? AND notifications.sender_id = ?", recipient_id, sender_id)
end

최신 정보:

모든 것은 Notification.class_method 대신 인스턴스 메소드로 current_user에서 호출됩니다. Btw. 사용자 테이블에는 현재 알림 수를 계산하는 "new_chat_notification",default: 0"new_other_notification", default: 0속성이 있습니다.

user.rb

  #check and decrease chat notification that happens between 2 given users (max 1)
  def decreasing_chat_notification_number(user)
    notification = self.notifications.between_chat_recipient(user).unchecked.first
    self.checking_and_decreasing_notification(notification) if notification.present?
  end

  #check and decrease task notifications that happens between 2 given users
  def decreasing_task_notification_number(user)
    self.notifications.task.between_other_recipient(user).unchecked.each do |notification|
      self.checking_and_decreasing_notification(notification)
    end
  end

  #check and decrease the post notification that belongs to a given post
  def decreasing_post_notification_number(post_id)
    self.notifications.this_post_comments(post_id).unchecked.each do |notification|
      self.checking_and_decreasing_notification(notification)
    end
  end

  def checking_and_decreasing_notification(notification)
    notification.check_notification
    if notification.notifiable_type == "Message"
      self.decrease_new_chat_notifications
      self.decreased_chat_number_pusher
    else
      self.decrease_new_other_notifications
      self.decreased_other_number_pusher
    end
  end

  def decrease_new_chat_notifications
    decrement!(:new_chat_notification) if self.new_chat_notification > 0
  end


  def decrease_new_other_notifications
    decrement!(:new_other_notification) if self.new_other_notification > 0
  end

  def decreased_chat_number_pusher
    number = self.new_chat_notification
    Pusher['private-'+ self.id.to_s].trigger('new_chat_notification', {:number => number})
  end

  def decreased_other_number_pusher
    number = self.new_other_notification
    Pusher['private-'+ self.id.to_s].trigger('new_other_notification', {:number => number})
  end

notification.rb

scope :not_chat, -> { where.not(notifiable_type: "Message") }
scope :chat, -> { where(notifiable_type: "Message") }
scope :task, -> { where(notifiable_type: "Task") }
scope :post, -> { where(notifiable_type: "Post") }
scope :checked, -> { where.not(checked_at: nil) }
scope :unchecked, -> { where(checked_at: nil) }

scope :this_post_comments, -> (post_id) do
  where("notifications.notifiable_id = ?", post_id)
end

scope :between_chat_recipient, -> (sender_id) do
  where("notifications.sender_id = ? AND notifications.notifiable_type = ?", sender_id, "Message")
end

scope :between_other_recipient, -> (sender_id) do
  where("notifications.sender_id = ? AND notifications.notifiable_type != ?", sender_id, "Message")
end

def check_notification #chat notification gets checked
  update_attribute(:checked_at, Time.zone.now) if self.checked_at.nil?
end
파스칼

try개체에 메시지를 보내려고 시도 하는 사용할 수 있습니다 . 객체가 응답하면 실행되고, 그렇지 않으면 무시됩니다.

string = "foo"
string.try(:length) # => 3
nil.try(:length) => nil

try!대신 사용 하는 것이 좋습니다 . 수신자가 메시지에 응답하지 않고 응답하지 않으면 발생합니다.nil

그러나 그것은 여기서 당신을별로 도움이되지 않을 것입니다.

반복하면 무언가 존재하는지 확인할 필요가 없습니다. 반복 할 수 있으며 연결이 "비어 있으면"아무 일도 일어나지 않습니다.

예를 들어 다음을 다시 작성할 수 있습니다 decreeasing_post_notification_number.

def self.decreeasing_post_notification_number(current_user, post)
  self.post.this_post_comments(current_user, post).unchecked.each do |notification|
    checking_and_decreasing_notification(notification)
  end
end

동일은 간다 decreasing_chat_notification_number가 호출 괜찮 IFF checking_and_decreasing_notification에 대한 each뿐 아니라first

여기에 전체 코드가 표시되지 않으므로 몇 가지 가정을해야합니다. 코드가 OO처럼 보이지 않습니다 ( self필요한 모든 값을 매개 변수로받는 메서드가 있습니다). 다음 중 하나로 리팩토링하는 것이 좋습니다.

  • 이 방법을 관련 모델의 동작 (방법)으로 만듭니다.
  • 단일 비즈니스 운영을 다루는 서비스 만들기

BTW : Time.zone.now그냥 사용하는 것이 아니라 사용하는 것이 좋습니다 Time.now!

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

이 루비 메서드를 리팩토링 할 수 있습니까?

분류에서Dev

팩토리 메소드 리턴 스프링 서비스

분류에서Dev

비동기 메서드의 일부를 람다로 리팩토링

분류에서Dev

메서드 서명 리팩토링

분류에서Dev

메서드 체인 리팩토링

분류에서Dev

Ruby에서 일반적인 메서드 인수 리팩토링

분류에서Dev

루비 클래스, 서브 클래스 및 팩토리 메소드

분류에서Dev

데이터 객체에서 jQuery 각 루프 리팩토링

분류에서Dev

AngularJS : 루프 내에서 팩토리 메서드 호출

분류에서Dev

비동기 태스크 스레드 리팩토링

분류에서Dev

Ruby : 메서드를 예측 된 메서드로 리팩토링

분류에서Dev

스트림에 서비스 호출로 루프에 대한 노하우 리팩토링?

분류에서Dev

Python에서 리팩토링 (Eclipse에서 새 메소드 추출)

분류에서Dev

루비에서 해시의 반복을 리팩토링하는 더 효율적인 방법이 있습니까?

분류에서Dev

ArrayList에서 HashMap으로 메서드 리팩토링

분류에서Dev

LinkedList를 사용하여 유사한 메서드 리팩토링

분류에서Dev

제네릭 메서드를 전달하여 리팩토링

분류에서Dev

indexOf를 사용하여 두 가지 메서드 리팩토링

분류에서Dev

typescript에서 긴 함수 리팩토링

분류에서Dev

Android에서 관찰자 리팩토링

분류에서Dev

Rails3에서 리팩토링

분류에서Dev

Ruby on Rails 4.2.3에서 리팩토링

분류에서Dev

내 루프 반응 구성 요소를 일반 자바 스크립트에서 typescript로 리팩토링

분류에서Dev

WCF 서비스 방법-단위 테스트 및 모의 리팩토링

분류에서Dev

방법의 순서를 리팩토링

분류에서Dev

VBA 리팩토링, 어디서나 MsgBox

분류에서Dev

mysql에 레코드 삽입 후 자동 메일 링 서비스

분류에서Dev

이미 간단한 루비 코드를 리팩토링하는 방법

분류에서Dev

절차 적에서 OOP로 레거시 리팩토링

Related 관련 기사

  1. 1

    이 루비 메서드를 리팩토링 할 수 있습니까?

  2. 2

    팩토리 메소드 리턴 스프링 서비스

  3. 3

    비동기 메서드의 일부를 람다로 리팩토링

  4. 4

    메서드 서명 리팩토링

  5. 5

    메서드 체인 리팩토링

  6. 6

    Ruby에서 일반적인 메서드 인수 리팩토링

  7. 7

    루비 클래스, 서브 클래스 및 팩토리 메소드

  8. 8

    데이터 객체에서 jQuery 각 루프 리팩토링

  9. 9

    AngularJS : 루프 내에서 팩토리 메서드 호출

  10. 10

    비동기 태스크 스레드 리팩토링

  11. 11

    Ruby : 메서드를 예측 된 메서드로 리팩토링

  12. 12

    스트림에 서비스 호출로 루프에 대한 노하우 리팩토링?

  13. 13

    Python에서 리팩토링 (Eclipse에서 새 메소드 추출)

  14. 14

    루비에서 해시의 반복을 리팩토링하는 더 효율적인 방법이 있습니까?

  15. 15

    ArrayList에서 HashMap으로 메서드 리팩토링

  16. 16

    LinkedList를 사용하여 유사한 메서드 리팩토링

  17. 17

    제네릭 메서드를 전달하여 리팩토링

  18. 18

    indexOf를 사용하여 두 가지 메서드 리팩토링

  19. 19

    typescript에서 긴 함수 리팩토링

  20. 20

    Android에서 관찰자 리팩토링

  21. 21

    Rails3에서 리팩토링

  22. 22

    Ruby on Rails 4.2.3에서 리팩토링

  23. 23

    내 루프 반응 구성 요소를 일반 자바 스크립트에서 typescript로 리팩토링

  24. 24

    WCF 서비스 방법-단위 테스트 및 모의 리팩토링

  25. 25

    방법의 순서를 리팩토링

  26. 26

    VBA 리팩토링, 어디서나 MsgBox

  27. 27

    mysql에 레코드 삽입 후 자동 메일 링 서비스

  28. 28

    이미 간단한 루비 코드를 리팩토링하는 방법

  29. 29

    절차 적에서 OOP로 레거시 리팩토링

뜨겁다태그

보관