Method: ModelFormatter.formatter_for

Defined in:
lib/model_formatter.rb

.formatter_for(type_name, options = {}) ⇒ Object

Return the formatter for a class, formatter object, symbol, or string defining the name of a formatter class. If it’s a symbol, check the Formatters module for the class that matches the camelized name of the symbol with ‘Format’ prepended. Options hash is passed to the instantiation of the formatter object.



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/model_formatter.rb', line 74

def self.formatter_for(type_name, options = {}) # :nodoc:
	# If the type_name is an instance of a formatter, just return with it
	return type_name if type_name.is_a? Formatters::Format

	# If the type_name is a class just assign it to the formatter_class for instantiation later
	formatter_class = type_name if type_name.is_a? Class

	# Format a symbol or string into a formatter_class
	if type_name.is_a? Symbol or type_name.is_a? String
		type_name = type_name.to_s.camelize

		# Construct the class name from the type_name
		formatter_name = "Format#{type_name}"
		formatter_class = nil
		begin
			formatter_class = Formatters.const_get(formatter_name)
		rescue NameError => ne
			# Ignore this, caught below
		end
	end

	# Make sure the name of this is found in the Formatters module and that
	# it's the correct superclass
	return formatter_class.new(options) unless formatter_class.nil? or
																							formatter_class.superclass != Formatters::Format

	raise Formatters::FormatNotFoundException.new("Cannot find formatter 'Formatters::#{formatter_name}'")
end