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


56
57
58
# File 'app/controllers/dry_crud/generic_model.rb', line 56

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.


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

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.


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

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.


24
25
26
# File 'app/controllers/dry_crud/generic_model.rb', line 24

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.


30
31
32
# File 'app/controllers/dry_crud/generic_model.rb', line 30

def path_args(last)
  last
end