Class: AcceptLanguage::Intersection

Inherits:
Object
  • Object
show all
Defined in:
lib/accept_language/intersection.rb

Overview

Note:

Compare an Accept-Language header value with your application’s supported languages to find the common languages that could be presented to a user.

Examples:

Intersection.new('da, en-gb;q=0.8, en;q=0.7', :ar, :ja, :ro).call

See Also:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(accepted_languages, default_supported_language, *other_supported_languages, truncate: true) ⇒ Intersection

Returns a new instance of Intersection.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/accept_language/intersection.rb', line 13

def initialize(accepted_languages, default_supported_language, *other_supported_languages, truncate: true)
  @accepted_languages         = Parser.new(accepted_languages).call
  @default_supported_language = default_supported_language.to_sym
  @other_supported_languages  = other_supported_languages.map(&:to_sym).to_set

  return unless truncate

  @accepted_languages = @accepted_languages.map do |accepted_language|
    accepted_language[0, 2].to_sym
  end

  @default_supported_language = @default_supported_language[0, 2].to_sym

  @other_supported_languages = @other_supported_languages.map do |other_supported_language|
    other_supported_language[0, 2].to_sym
  end.to_set
end

Instance Attribute Details

#accepted_languagesObject (readonly)

Returns the value of attribute accepted_languages.



11
12
13
# File 'lib/accept_language/intersection.rb', line 11

def accepted_languages
  @accepted_languages
end

#default_supported_languageObject (readonly)

Returns the value of attribute default_supported_language.



11
12
13
# File 'lib/accept_language/intersection.rb', line 11

def default_supported_language
  @default_supported_language
end

#other_supported_languagesObject (readonly)

Returns the value of attribute other_supported_languages.



11
12
13
# File 'lib/accept_language/intersection.rb', line 11

def other_supported_languages
  @other_supported_languages
end

Instance Method Details

#callObject



31
32
33
34
35
36
37
# File 'lib/accept_language/intersection.rb', line 31

def call
  accepted_languages.find do |accepted_language|
    break default_supported_language if accepted_language.equal?(wildcard)

    supported_languages.include?(accepted_language)
  end
end