Class: XRB::Formatters::Formatter

Inherits:
Mapping::Model
  • Object
show all
Defined in:
lib/xrb/formatters/formatter.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Formatter

Returns a new instance of Formatter.



17
18
19
20
21
# File 'lib/xrb/formatters/formatter.rb', line 17

def initialize(**options)
	@options = options
	
	@object = nil
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



65
66
67
# File 'lib/xrb/formatters/formatter.rb', line 65

def options
  @options
end

Class Method Details

.for(object, **options) ⇒ Object



13
14
15
# File 'lib/xrb/formatters/formatter.rb', line 13

def self.for(object, **options)
	self.new(object: object, **options)
end

Instance Method Details

#[](key) ⇒ Object



83
84
85
# File 'lib/xrb/formatters/formatter.rb', line 83

def [] key
	@options[key]
end

#format(object, **options) ⇒ Object Also known as: text



71
72
73
74
75
76
77
78
79
# File 'lib/xrb/formatters/formatter.rb', line 71

def format(object, **options)
	method_name = self.method_for_mapping(object)
	
	if self.respond_to?(method_name)
		self.send(method_name, object, **options)
	else
		format_unspecified(object, **options)
	end
end

#format_unspecified(object, **options) ⇒ Object



67
68
69
# File 'lib/xrb/formatters/formatter.rb', line 67

def format_unspecified(object, **options)
	object.to_s
end

#name_for(**options) ⇒ Object

The name of the field, used for the name attribute of an input.



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/xrb/formatters/formatter.rb', line 33

def name_for(**options)
	name = options[:name] || options[:field]
	
	if suffix = options[:suffix]
		name = "#{name}#{suffix}"
	end
	
	if nested_name = self.nested_name(**options)
		"#{nested_name}[#{name}]"
	else
		name
	end
end

#nested(name, key = name, klass: self.class) {|formatter| ... } ⇒ Object

Yields:

  • (formatter)


51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/xrb/formatters/formatter.rb', line 51

def nested(name, key = name, klass: self.class)
	options = @options.dup
	target = self.object.send(name)
	
	options[:object] = target
	options[:nested_name] = nested_name_for(name: key)
	
	formatter = klass.new(**options)
	
	return formatter unless block_given?
	
	yield formatter
end

#nested_name(**options) ⇒ Object



28
29
30
# File 'lib/xrb/formatters/formatter.rb', line 28

def nested_name(**options)
	options[:nested_name] || @options[:nested_name]
end

#nested_name_for(**options) ⇒ Object



47
48
49
# File 'lib/xrb/formatters/formatter.rb', line 47

def nested_name_for(**options)
	name_for(**options)
end

#objectObject

The target object of the form.



24
25
26
# File 'lib/xrb/formatters/formatter.rb', line 24

def object
	@object ||= @options[:object]
end