Class: Trenni::Formatters::Formatter

Inherits:
Mapping::Model
  • Object
show all
Defined in:
lib/trenni/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.



34
35
36
37
38
# File 'lib/trenni/formatters/formatter.rb', line 34

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

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



82
83
84
# File 'lib/trenni/formatters/formatter.rb', line 82

def options
  @options
end

Class Method Details

.for(object, **options) ⇒ Object



30
31
32
# File 'lib/trenni/formatters/formatter.rb', line 30

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

Instance Method Details

#[](key) ⇒ Object



100
101
102
# File 'lib/trenni/formatters/formatter.rb', line 100

def [] key
	@options[key]
end

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



88
89
90
91
92
93
94
95
96
# File 'lib/trenni/formatters/formatter.rb', line 88

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



84
85
86
# File 'lib/trenni/formatters/formatter.rb', line 84

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.



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

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)


68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/trenni/formatters/formatter.rb', line 68

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



45
46
47
# File 'lib/trenni/formatters/formatter.rb', line 45

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

#nested_name_for(**options) ⇒ Object



64
65
66
# File 'lib/trenni/formatters/formatter.rb', line 64

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

#objectObject

The target object of the form.



41
42
43
# File 'lib/trenni/formatters/formatter.rb', line 41

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