Class: Optionize

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(given, *names) ⇒ Optionize



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/optionize.rb', line 4

def initialize(given, *names)
  static  = names.last.respond_to?(:merge) ? names.pop : {}
  dynamic = given.last.respond_to?(:merge) ? given.pop : {}

  @names = names.map{|i| i.to_s}
  @hash  = {}

  # static
  static.each_pair{|key, val| self[key] = val }

  # dynamic
  dynamic.each_pair{|key, val| self[key] = val }

  # given
  given.each_with_index do |value, i|
    key = names[i] or
      raise IndexError, "expected %d args but got %s %s" % [names.size, i+1, given.inspect]
    self[key] = value
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object (private)



42
43
44
45
46
47
48
# File 'lib/optionize.rb', line 42

def method_missing(name, *args)
  if name.to_s =~ /(.*)=$/
    self[$1] = args.first
  else
    self[name]
  end
end

Instance Attribute Details

#namesObject (readonly)

Returns the value of attribute names.



2
3
4
# File 'lib/optionize.rb', line 2

def names
  @names
end

Instance Method Details

#[](key) ⇒ Object



29
30
31
# File 'lib/optionize.rb', line 29

def [](key)
  @hash[key.to_s]
end

#[]=(key, val) ⇒ Object



33
34
35
# File 'lib/optionize.rb', line 33

def []=(key, val)
  @hash[key.to_s] = val
end

#named_valuesObject



37
38
39
# File 'lib/optionize.rb', line 37

def named_values
  names.map{|name| self[name]}
end

#to_hashObject



25
26
27
# File 'lib/optionize.rb', line 25

def to_hash
  @hash
end