Module: ViewModels::Helpers::Mapping

Defined in:
lib/view_models/helpers/collection.rb,
lib/view_models/helpers/mapping.rb

Overview

Mapping helpers install collection_view_model_for and view_model_for, which you can use with instances to conveniently instantiate a view model for it

Defined Under Namespace

Classes: Collection

Instance Method Summary (collapse)

Instance Method Details

- (Object) collection_view_model_for(array_or_pagination, context = self)

TODO:

Think about moving it into view_model_for, or renaming it view_models_for.

Construct a view_model for a collection.



16
17
18
# File 'lib/view_models/helpers/collection.rb', line 16

def collection_view_model_for array_or_pagination, context = self
  Collection.new array_or_pagination, context
end

- (Object) default_view_model_class_for(model)

Returns the default view_model class for the given model instance.

Default class name is: ViewModels::<ModelClassName>

Override this method if you'd like to change the default model-to-view_model class mapping.

Raises:

  • (NameError)

    if a corresponding ViewModels constant cannot be loaded.



42
43
44
# File 'lib/view_models/helpers/mapping.rb', line 42

def default_view_model_class_for model
  (default_prefix + model.class.name).constantize
end

- (Object) specific_view_model_class_for(model)

Returns a specific view_model class for the given model instance.

Override this method, if you want to return a specific view model class for the given model.

Raises:

  • (NameError)

    if a corresponding ViewModels constant cannot be loaded.



53
54
55
# File 'lib/view_models/helpers/mapping.rb', line 53

def specific_view_model_class_for model
  specific_view_model_mapping[model.class]
end

- (Object) view_model_class_for(model)

Note:

ViewModels are usually of class ViewModels::<ModelClassName>. (As returned by default_view_model_class_for). Override specific_mapping if you'd like to install your own. Or Override default_view_model_class_for(model) if you'd like to change the default.

Get the view_model class for the given model instance.



28
29
30
# File 'lib/view_models/helpers/mapping.rb', line 28

def view_model_class_for model
  specific_view_model_class_for(model) || default_view_model_class_for(model)
end

- (Object) view_model_for(model, context = self)

Note:

context is either a view instance or a controller instance.

Create a new view_model instance for the given model instance with the given arguments.

Raises:

  • (ArgumentError)

    if the view model class doesn't support 2 arguments.



20
21
22
# File 'lib/view_models/helpers/mapping.rb', line 20

def view_model_for model, context = self
  view_model_class_for(model).new model, context
end