Class: Deeplink::Link

Inherits:
Object
  • Object
show all
Defined in:
lib/deeplink/link.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri) ⇒ Link

Returns a new instance of Link.



13
14
15
16
17
18
19
20
21
22
# File 'lib/deeplink/link.rb', line 13

def initialize(uri)
  return unless uri

  uri = parse(uri)

  self.scheme = uri.scheme
  self.path = uri.path

  @query = sanitize(parse_query(uri.query)) if uri.query
end

Instance Attribute Details

#pathObject

Returns the value of attribute path.



8
9
10
# File 'lib/deeplink/link.rb', line 8

def path
  @path
end

#queryObject (readonly)

To add and remove items to the query string use #add_query and #remove_query



11
12
13
# File 'lib/deeplink/link.rb', line 11

def query
  @query
end

#schemeObject

Returns the value of attribute scheme.



8
9
10
# File 'lib/deeplink/link.rb', line 8

def scheme
  @scheme
end

Instance Method Details

#add_query(hash) ⇒ Object

Add query parameters to the link. You can add one or more parameters since this method receives a hash.

Example

deeplink = Deeplink.parse("link://directions")

deeplink.add_query(lat: 38.7179233, lon: -9.150129)

deeplink.to_s # => "link://directions?lat=38.7179233&lon=-9.150129"


34
35
36
37
38
# File 'lib/deeplink/link.rb', line 34

def add_query(hash)
  @query ||= {}

  @query.merge!(sanitize(hash))
end

#query?Boolean Also known as: has_query?

Returns true if the link has a query string or false otherwise

Example

deeplink = Deeplink.parse("link://directions")

deeplink.query?             # => false

deeplink.add_query(foo: "bar")  # => { :foo => "bar" }

deeplink.query?             # => true

Returns:

  • (Boolean)


71
72
73
74
75
# File 'lib/deeplink/link.rb', line 71

def query?
  return false unless query

  !query.empty?
end

#remove_query(*keys) ⇒ Object

Removes query parameters by its keys. You can remove one or more parameters, sending a list of keys.

Example

deeplink = Deeplink.parse("link://directions?lat=38.7179233&lon=-9.150129&test=true")

deeplink.remove_query(:test) # => "true"

deeplink.remove_query(:lat, :lon) # => [38.7179233, -9.150129]


50
51
52
53
54
55
56
57
58
# File 'lib/deeplink/link.rb', line 50

def remove_query(*keys)
  return unless query

  if keys.size > 1
    keys.map { |key| query.delete(key.to_sym) }
  else
    query.delete(keys.first.to_sym)
  end
end

#to_sObject

Returns the link as a String



80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/deeplink/link.rb', line 80

def to_s
  return '' unless scheme && path

  uri = "#{scheme}:/#{path}"

  if query?
    query_string = query.map { |key, value| "#{key}=#{value}" }.join('&')

    uri += "?#{query_string}"
  end

  uri
end