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 },
}
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
68
69
70
71
72
73
74
75
|
# File 'lib/structr.rb', line 68
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
60
61
62
63
64
65
66
|
# File 'lib/structr.rb', line 60
def converter(name, proc=nil, &block)
if block = proc || block
Converter[name] = block
else
Converter[name]
end
end
|
#field(name, regexp, options = {}, &block) ⇒ Object
17
18
19
20
21
22
23
24
25
26
27
28
|
# File 'lib/structr.rb', line 17
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
30
31
32
|
# File 'lib/structr.rb', line 30
def field_accessor(name, regexp, &block)
field(name, regexp, :accessor => true, &block)
end
|
#field_reader(name, regexp, &block) ⇒ Object
34
35
36
|
# File 'lib/structr.rb', line 34
def field_reader(name, regexp, &block)
field(name, regexp, :accessor => :reader, &block)
end
|
#field_writer(name, regexp, &block) ⇒ Object
38
39
40
|
# File 'lib/structr.rb', line 38
def field_writer(name, regexp, &block)
field(name, regexp, :accessor => :writer, &block)
end
|
#fields ⇒ Object
42
43
44
|
# File 'lib/structr.rb', line 42
def fields
@fields ||= []
end
|
#structr(content, *options) ⇒ Object
46
47
48
49
50
51
52
53
54
55
56
57
58
|
# File 'lib/structr.rb', line 46
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
|