Module: Structr::ClassMethods
- Defined in:
- lib/structr.rb
Constant Summary
collapse
- Converter =
{
:int => proc { |m| m.to_i },
:float => proc { |m| m.to_f },
:date => proc { |m| ::Date.parse(m) },
:string => proc { |m| m.to_s },
}
Instance Method Summary
collapse
-
#converter(name, proc = nil, &block) ⇒ Object
-
#field(name, regexp, options = {}, &block) ⇒ Object
-
#field_accessor(name, regexp, &block) ⇒ Object
-
#field_reader(name, regexp, &block) ⇒ Object
-
#field_writer(name, regexp, &block) ⇒ Object
-
#fields ⇒ Object
-
#method_missing(method, *args, &block) ⇒ Object
-
#structr(content, *options) ⇒ Object
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
69
70
71
72
73
74
75
76
|
# File 'lib/structr.rb', line 69
def method_missing(method, *args, &block)
name = method.to_s.gsub(/_(accessor|reader|writer)/, '')
if converter = converter(name.to_sym)
field(args[0], args[1], :accessor => $1 ? $1.to_sym : nil, &converter)
else
super(method, *args, &block)
end
end
|
Instance Method Details
#converter(name, proc = nil, &block) ⇒ Object
61
62
63
64
65
66
67
|
# File 'lib/structr.rb', line 61
def converter(name, proc=nil, &block)
if block = proc || block
Converter[name] = block
else
Converter[name]
end
end
|
#field(name, regexp, options = {}, &block) ⇒ Object
18
19
20
21
22
23
24
25
26
27
28
29
|
# File 'lib/structr.rb', line 18
def field(name, regexp, options={}, &block)
fields << FieldDefinition.new(name, regexp, &block)
case options[:accessor]
when :reader
attr_reader(name)
when :writer
attr_writer(name)
when :accessor, true
attr_accessor(name)
end
end
|
#field_accessor(name, regexp, &block) ⇒ Object
31
32
33
|
# File 'lib/structr.rb', line 31
def field_accessor(name, regexp, &block)
field(name, regexp, :accessor => true, &block)
end
|
#field_reader(name, regexp, &block) ⇒ Object
35
36
37
|
# File 'lib/structr.rb', line 35
def field_reader(name, regexp, &block)
field(name, regexp, :accessor => :reader, &block)
end
|
#field_writer(name, regexp, &block) ⇒ Object
39
40
41
|
# File 'lib/structr.rb', line 39
def field_writer(name, regexp, &block)
field(name, regexp, :accessor => :writer, &block)
end
|
#fields ⇒ Object
43
44
45
|
# File 'lib/structr.rb', line 43
def fields
@fields ||= []
end
|
#structr(content, *options) ⇒ Object
47
48
49
50
51
52
53
54
55
56
57
58
59
|
# File 'lib/structr.rb', line 47
def structr(content, *options)
instance = new(*options)
fields.each do |field|
value = field.match(content)
value = value.first if value.size < 2
if instance.respond_to?(field.setter)
instance.send(field.setter, value)
else
instance.instance_variable_set(field.ivar, value)
end
end
instance
end
|