Class: FavoriteRestaurantService

Inherits:
Object
  • Object
show all
Includes:
DefaultErrorContainer
Defined in:
app/services/favorite_restaurant_service.rb

Overview

CRUD interface for user to manage their favorites restaurant list TODO add pagination support for #index and #index_ids

Instance Method Summary collapse

Methods included from DefaultErrorContainer

#error, #error_message_simple, #merge_errors

Constructor Details

#initialize(user_id) ⇒ FavoriteRestaurantService

Returns a new instance of FavoriteRestaurantService.



10
11
12
# File 'app/services/favorite_restaurant_service.rb', line 10

def initialize(user_id)
  self.user_id = user_id
end

Instance Method Details

#add(restaurant_id) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'app/services/favorite_restaurant_service.rb', line 22

def add(restaurant_id)
  fav = Fav.find_or_initialize_by restaurant_id: restaurant_id, user_id: user_id
  unless fav.new_record?
    error.add(:base, 'Restaurant ID already added to favorite list')
    return false
  end
  return true if fav.save

  error.add(:base, fav.errors.full_messages.to_sentence)
  false
end

#indexObject



18
19
20
# File 'app/services/favorite_restaurant_service.rb', line 18

def index
  index_query
end

#index_idsObject



14
15
16
# File 'app/services/favorite_restaurant_service.rb', line 14

def index_ids
  Kaminari.paginate_array(index_query.pluck(:id))
end

#remove(restaurant_id) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/services/favorite_restaurant_service.rb', line 34

def remove(restaurant_id)
  fav = Fav.find_by restaurant_id: restaurant_id, user_id: user_id
  if fav.blank?
    error.add(:base, 'Restaurant ID not found from favorite list')
    return false
  end

  return true if fav.destroy

  error.add(:base, fav.errors.full_messages.to_sentence)
  false
end

#toggle(restaurant_id) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'app/services/favorite_restaurant_service.rb', line 47

def toggle(restaurant_id)
  fav = Fav.find_or_initialize_by restaurant_id: restaurant_id, user_id: user_id
  result = if fav.new_record?
             @toggle_message = I18n.t('actions.favorites_restaurant.added')
             fav.save
           else
             @toggle_message = I18n.t('actions.favorites_restaurant.removed')
             fav.destroy
           end

  error.add(:base, fav.errors.full_messages.to_sentence) unless result

  result
rescue ActiveRecord::RecordNotUnique
  # silently return true because the record is already there
  true
end

#toggle_messageObject



65
66
67
# File 'app/services/favorite_restaurant_service.rb', line 65

def toggle_message
  @toggle_message ||= ''
end