简体   繁体   中英

How to correctly refactor the code:

I'm creating a like model in my rails application.Firstly I wrote something like this:

- if BonusLikePolicy.new(current_user, bonus).create?
      = link_to bonus_likes_path(bonus), method: :delete,
                data: { remote: true, behavior: "fragments" } do
        span.dislike
    - else
      = link_to bonus_likes_path(bonus), method: :post,
                data: { remote: true, behavior: "fragments" } do
        span.like

It works fine, but as you see here's a couple of repeating. So I needed to make it DRY and rewrite to:

= bonus.link_to_like(bonus, current_user)

And create the method to bonus:

def link_to_like(bonus, user)
    options = { class: "like", method: :post }
    options = { class: "dislike", method: :delete } unless BonusLikePolicy.new(user, bonus).create?

    h.link_to(
      h.tag(:span, class: options[:class]), h.bonus_likes_path(bonus),
      method: options[:method], data: { remote: true, behavior: "fragments" }
    )
  end

I've got an error, undefined method destroy for nil class. Maybe I missed something but cannot find it. Please help :)

UPD:

Also my span icons didn't show correctly(it means class that i pass in h.tag also not passed)

NoMethodError (undefined method `destroy' for nil:NilClass):


app/controllers/likes_controller.rb:12:in `destroy'

As per the logic you have in your working code snippet

Replace unless with if

options = { class: "dislike", method: :delete } if  BonusLikePolicy.new(user, bonus).create?

I don't like overriding options. In my opinion better do sth like

Step 1.

options = (!BonusLikePolicy.new(user, bonus).create? ? { class: "dislike", method: :delete } : { class: "like", method: :post })

Step 2. make private method

def can_not_create_like?
  !BonusLikePolicy.new(user, bonus).create?
end

Step 3.

options = (can_not_create_like? ? { class: "dislike", method: :delete } : { class: "like", method: :post })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM