Class: Formtastic::NamespacedClassFinder

Inherits:
Object
  • Object
show all
Defined in:
lib/formtastic/namespaced_class_finder.rb

Overview

This class implements class resolution in a namespace chain. It is used both by Formtastic::Helpers::InputHelper and Formtastic::Helpers::ActionHelper to look up action and input classes.

==== Example You can implement own class finder that for example prefixes the class name or uses custom module.

class MyInputClassFinder < Formtastic::NamespacedClassFinder def initialize(builder) super [MyNamespace, Object] # first lookup in MyNamespace then the globals end

private

def class_name(as)
  "My#{super}Input" # for example MyStringInput
end

end

And then set Formtastic::FormBuilder.input_class_finder with that class.

Direct Known Subclasses

ActionClassFinder, InputClassFinder

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(namespaces) ⇒ NamespacedClassFinder

:nodoc:



31
32
33
34
# File 'lib/formtastic/namespaced_class_finder.rb', line 31

def initialize(namespaces) #:nodoc:
  @namespaces = namespaces.flatten
  @cache = {}
end

Instance Attribute Details

#namespacesObject (readonly)

:nodoc:



25
26
27
# File 'lib/formtastic/namespaced_class_finder.rb', line 25

def namespaces
  @namespaces
end

Instance Method Details

#find(as) ⇒ Object

Looks up the given reference in the configured namespaces.

Two finder methods are provided, one for development tries to reference the constant directly, triggering Rails' autoloading const_missing machinery; the second one instead for production checks with .const_defined before referencing the constant.



43
44
45
# File 'lib/formtastic/namespaced_class_finder.rb', line 43

def find(as)
  @cache[as] ||= resolve(as)
end

#resolve(as) ⇒ Object



47
48
49
50
51
# File 'lib/formtastic/namespaced_class_finder.rb', line 47

def resolve(as)
  class_name = class_name(as)

  finder(class_name) or raise NotFoundError, "class #{class_name}"
end