Class: Atig::Option

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table) ⇒ Option

Returns a new instance of Option.



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/atig/option.rb', line 36

def initialize(table)
  @table = {}
  table.each do|key,value|
    key = key.to_sym
    @table[key] = value
    new_ostruct_member key
  end

  # Ruby 1.8だとidというフィールドが作れないので作っておく
  new_ostruct_member :id, true
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(mid, *args) ⇒ Object

:nodoc:



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/atig/option.rb', line 70

def method_missing(mid, *args) # :nodoc:
  mname = mid.id2name
  len = args.length
  if mname =~ /=$/
    if len != 1
      raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
    end
    if self.frozen?
      raise TypeError, "can't modify frozen #{self.class}", caller(1)
    end
    name = mname.chop.to_sym
    @table[name] = args[0]
    self.new_ostruct_member(name)
  elsif len == 0
    @table[mid]
  else
    raise NoMethodError, "undefined method `#{mname}' for #{self}", caller(1)
  end
end

Class Method Details

.default_value(name, value) ⇒ Object



5
6
7
8
# File 'lib/atig/option.rb', line 5

def default_value(name, value)
  @default ||= {}
  @default[name.to_sym] = value
end

.parse(str) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/atig/option.rb', line 10

def parse(str)
  @default ||= {}
  opts = str.split(" ")
  opts = opts.inject({}) do |r, i|
    key, value = i.split("=", 2)

    r.update key.to_sym => parse_value(value)
  end
  self.new(@default.merge(opts))
end

.parse_value(value) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/atig/option.rb', line 21

def parse_value(value)
  case value
  when nil, /\Atrue\z/          then true
  when /\Afalse\z/              then false
  when /\A\d+\z/                then value.to_i
  when /\A(?:\d+\.\d*|\.\d+)\z/ then value.to_f
  else                               value
  end
end

Instance Method Details

#[](name) ⇒ Object



53
54
55
# File 'lib/atig/option.rb', line 53

def [](name)
  @table[name.to_sym]
end

#[]=(name, value) ⇒ Object



57
58
59
# File 'lib/atig/option.rb', line 57

def []=(name, value)
  @table[name.to_sym] = value
end

#fieldsObject



49
50
51
# File 'lib/atig/option.rb', line 49

def fields;
  @table.keys
end

#marshal_dumpObject



48
# File 'lib/atig/option.rb', line 48

def marshal_dump; @table end

#new_ostruct_member(name, force = false) ⇒ Object



61
62
63
64
65
66
67
68
# File 'lib/atig/option.rb', line 61

def new_ostruct_member(name, force=false)
  if force or (not self.respond_to?(name))
    class << self; self; end.class_eval do
      define_method(name) { @table[name] }
      define_method(:"#{name}=") { |x| @table[name] = x }
    end
  end
end