Class: HungryHub::Restaurant::Codec

Inherits:
Object
  • Object
show all
Defined in:
app/my_lib/hungry_hub/restaurant/codec.rb

Constant Summary collapse

SEPARATOR =
'::'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(restaurant: nil, hash: nil) ⇒ Codec

Returns a new instance of Codec.



9
10
11
12
13
14
15
16
17
18
# File 'app/my_lib/hungry_hub/restaurant/codec.rb', line 9

def initialize(restaurant: nil, hash: nil)
  if restaurant.present?
    @restaurant = if restaurant.is_a?(::Restaurant)
                    restaurant
                  else
                    ::Restaurant.fetch(restaurant)
                  end
  end
  @hash = hash if hash
end

Instance Attribute Details

#hashObject

Returns the value of attribute hash.



6
7
8
# File 'app/my_lib/hungry_hub/restaurant/codec.rb', line 6

def hash
  @hash
end

#restaurantObject

Returns the value of attribute restaurant.



6
7
8
# File 'app/my_lib/hungry_hub/restaurant/codec.rb', line 6

def restaurant
  @restaurant
end

Class Method Details

.decode(hash) ⇒ Object



42
43
44
# File 'app/my_lib/hungry_hub/restaurant/codec.rb', line 42

def self.decode(hash)
  new(hash: hash).decode
end

.encode(restaurant) ⇒ Object



38
39
40
# File 'app/my_lib/hungry_hub/restaurant/codec.rb', line 38

def self.encode(restaurant)
  new(restaurant: restaurant).encode
end

Instance Method Details

#decodeObject



24
25
26
27
28
29
30
# File 'app/my_lib/hungry_hub/restaurant/codec.rb', line 24

def decode
  id = ::Restaurant.decrypt_id(::CGI.unescape(hash))
  return id unless id.nil?
  old_way
rescue Hashids::InputError
  old_way
end

#encodeObject



20
21
22
# File 'app/my_lib/hungry_hub/restaurant/codec.rb', line 20

def encode
  URI.encode_www_form_component restaurant.friendly_id
end

#old_wayObject



32
33
34
35
36
# File 'app/my_lib/hungry_hub/restaurant/codec.rb', line 32

def old_way
  id = Base64.decode64(::CGI.unescape(hash)).to_s.split(SEPARATOR).first.to_i
  return false if id.zero?
  id
end