Class: Lastfm::Util

Inherits:
Object
  • Object
show all
Defined in:
lib/lastfm/util.rb

Class Method Summary collapse

Class Method Details

.build_options(args, mandatory, optional) ⇒ Object


7
8
9
10
11
12
13
# File 'lib/lastfm/util.rb', line 7

def self.build_options(args, mandatory, optional)
  if args.first.is_a?(Hash)
    build_options_from_hash(args.first, mandatory || [], optional || [])
  else
    build_options_from_array(args, mandatory || [], optional || [])
  end
end

.build_options_from_array(values, mandatory, optional) ⇒ Object


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/lastfm/util.rb', line 33

def self.build_options_from_array(values, mandatory, optional)
  options = {}

  mandatory.each_with_index do |name, index|
    raise ArgumentError.new('%s is required' % name) unless values[index]
    options[name] = values[index]
  end

  optional.each_with_index do |name, index|
    value = name[1]
    if value.kind_of?(Proc)
      value = value.call
    end
    options[name[0]] = values[index + mandatory.size] || value
  end

  options
end

.build_options_from_hash(options, mandatory, optional) ⇒ Object


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/lastfm/util.rb', line 15

def self.build_options_from_hash(options, mandatory, optional)
  candidates = mandatory.kind_of?(AnyParams) ? mandatory.candidates : [mandatory]
  candidates.each do |params|
    missing_param = Array(params).any? { |param| !options.key?(param) }
    if missing_param && params.equal?(candidates.last)
      raise ArgumentError.new("%s is required" % candidates.map{ |c| Array(c).join(', ')}.join(' or '))
    end

    break unless missing_param
  end

  optional.each do |name, value|
    options[name] ||= value.kind_of?(Proc) ? value.call : value
  end

  options
end

.force_array(array_or_something) ⇒ Object


3
4
5
# File 'lib/lastfm/util.rb', line 3

def self.force_array(array_or_something)
  array_or_something.kind_of?(Array) ? array_or_something : [array_or_something].compact
end