Module: DryCrud::GenericModel

Extended by:
ActiveSupport::Concern
Included in:
ListController
Defined in:
app/controllers/dry_crud/generic_model.rb

Overview

Connects the including controller to the model whose name corrsponds to the controller’s name.

The two main methods are model_class and model_scope. Additional helper methods store and retrieve values in instance variables named after their class.

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#ivar_name(klass) ⇒ Object



54
55
56
# File 'app/controllers/dry_crud/generic_model.rb', line 54

def ivar_name(klass)
  klass.model_name.param_key
end

#model_ivar_get(plural: false) ⇒ Object

Get the instance variable named after the model_class. If the collection variable is required, pass true as the second argument.



34
35
36
37
38
39
# File 'app/controllers/dry_crud/generic_model.rb', line 34

def model_ivar_get(plural: false)
  name = ivar_name(model_class)
  name = name.pluralize if plural
  name = :"@#{name}"
  instance_variable_get(name) if instance_variable_defined?(name)
end

#model_ivar_set(value) ⇒ Object

Sets an instance variable with the underscored class name if the given value. If the value is a collection, sets the plural name.



43
44
45
46
47
48
49
50
51
52
# File 'app/controllers/dry_crud/generic_model.rb', line 43

def model_ivar_set(value)
  name = if value.respond_to?(:klass) # ActiveRecord::Relation
           ivar_name(value.klass).pluralize
         elsif value.respond_to?(:each) # Array
           ivar_name(value.first.class).pluralize
         else
           ivar_name(value.class)
         end
  instance_variable_set(:"@#{name}", value)
end

#model_scopeObject

The scope where model entries will be listed and created. This is mainly used for nested models to provide the required context.



22
23
24
# File 'app/controllers/dry_crud/generic_model.rb', line 22

def model_scope
  model_class.all
end

#path_args(last) ⇒ Object

The path arguments to link to the given model entry. If the controller is nested, this provides the required context.



28
29
30
# File 'app/controllers/dry_crud/generic_model.rb', line 28

def path_args(last)
  last
end