Class: Avo::Resources::Base

Direct Known Subclasses

BaseResource

Constant Summary collapse

VIEW_METHODS_MAPPING =
{
  index: [:index_fields, :display_fields],
  show: [:show_fields, :display_fields],
  edit: [:edit_fields, :form_fields],
  update: [:edit_fields, :form_fields],
  new: [:new_fields, :form_fields],
  create: [:new_fields, :form_fields]
}

Instance Attribute Summary collapse

Attributes included from Concerns::HasItems

#items_holder

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Concerns::ControlsPlacement

#controls_placement_calculated, #resource_controls_render_on_the_left?, #resource_controls_render_on_the_right?

Methods included from Concerns::Pagination

#apply_pagination, #pagination_type

Methods included from Concerns::HasHelpers

#helpers

Methods included from Concerns::HasProfilePhoto

#profile_photo

Methods included from Concerns::HasCoverPhoto

#cover_photo

Methods included from Concerns::HasDescription

#description

Methods included from Concerns::HasResourceStimulusControllers

#add_stimulus_attributes_for, #get_stimulus_controllers, #stimulus_data_attributes

Methods included from Concerns::HasControls

#render_edit_controls, #render_index_controls, #render_row_controls, #render_show_controls

Methods included from Concerns::CanReplaceItems

#with_new_items

Methods included from Concerns::HasItems

#fields, #get_field, #get_field_definitions, #get_fields, #get_items, #get_preview_fields, #invalid_fields, #is_empty?, #items, #only_fields, #tab_groups, #visible_items

Constructor Details

#initialize(record: nil, view: nil, user: nil, params: nil) ⇒ Base

Returns a new instance of Base.



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/avo/resources/base.rb', line 258

def initialize(record: nil, view: nil, user: nil, params: nil)
  @view = Avo::ViewInquirer.new(view) if view.present?
  @user = user if user.present?
  @params = params if params.present?

  if record.present?
    @record = record

    hydrate_model_with_default_values if @view&.new?
  end

  unless self.class.model_class.present?
    if model_class.present? && model_class.respond_to?(:base_class)
      self.class.model_class = model_class.base_class
    end
  end
end

Instance Attribute Details

#recordObject

Returns the value of attribute record.



47
48
49
# File 'lib/avo/resources/base.rb', line 47

def record
  @record
end

#reflectionObject

Returns the value of attribute reflection.



45
46
47
# File 'lib/avo/resources/base.rb', line 45

def reflection
  @reflection
end

#userObject

Returns the value of attribute user.



46
47
48
# File 'lib/avo/resources/base.rb', line 46

def user
  @user
end

#viewObject

Returns the value of attribute view.



44
45
46
# File 'lib/avo/resources/base.rb', line 44

def view
  @view
end

Class Method Details

.action(action_class, arguments: {}) ⇒ Object



91
92
93
# File 'lib/avo/resources/base.rb', line 91

def action(action_class, arguments: {})
  deprecated_dsl_api __method__, "actions"
end

.authorizationObject



120
121
122
# File 'lib/avo/resources/base.rb', line 120

def authorization
  Avo::Services::AuthorizationService.new Avo::Current.user, model_class, policy_class: authorization_policy
end

.class_nameObject



165
166
167
# File 'lib/avo/resources/base.rb', line 165

def class_name
  @class_name ||= to_s.demodulize
end

.fetch_search(key, record: nil) ⇒ Object



242
243
244
245
# File 'lib/avo/resources/base.rb', line 242

def fetch_search(key, record: nil)
  # self.class.fetch_search
  Avo::ExecutionContext.new(target: search[key], resource: self, record: record).handle
end

.filter(filter_class, arguments: {}) ⇒ Object



95
96
97
# File 'lib/avo/resources/base.rb', line 95

def filter(filter_class, arguments: {})
  deprecated_dsl_api __method__, "filters"
end

.find_record(id, query: nil, params: nil) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/avo/resources/base.rb', line 213

def find_record(id, query: nil, params: nil)
  query ||= find_scope # If no record is given we'll use the default

  if single_includes.present?
    query = query.includes(*single_includes)
  end

  if single_attachments.present?
    single_attachments.each do |attachment|
      query = query.send(:"with_attached_#{attachment}")
    end
  end

  Avo::ExecutionContext.new(
    target: find_record_method,
    query: query,
    id: id,
    params: params
  ).handle
end

.find_scopeObject

This resolves the scope when finding records (not “where” queries)

It’s used to apply the authorization feature.



116
117
118
# File 'lib/avo/resources/base.rb', line 116

def find_scope
  authorization.apply_policy model_class
end

.get_available_modelsObject



132
133
134
# File 'lib/avo/resources/base.rb', line 132

def get_available_models
  ApplicationRecord.descendants
end

.get_model_by_name(model_name) ⇒ Object



136
137
138
139
140
# File 'lib/avo/resources/base.rb', line 136

def get_model_by_name(model_name)
  get_available_models.find do |m|
    m.to_s == model_name.to_s
  end
end

.model_class(record_class: nil) ⇒ Object

Returns the model class being used for this resource.

The Resource instance has a model_class method too so it can support the STI use cases where we figure out the model class from the record



146
147
148
149
150
151
152
153
154
155
# File 'lib/avo/resources/base.rb', line 146

def model_class(record_class: nil)
  # get the model class off of the static property
  return constantized_model_class if @model_class.present?

  # get the model class off of the record for STI models
  return record_class if record_class.present?

  # generate a model class
  class_name.safe_constantize
end

.model_keyObject

This is used as the model class ID We use this instead of the route_key to maintain compatibility with uncountable models With uncountable models route key appends an _index suffix (Fish->fish_index) Example: User->users, MediaItem->media_items, Fish->fish



161
162
163
# File 'lib/avo/resources/base.rb', line 161

def model_key
  @model_key ||= model_class.model_name.plural
end

.nameObject Also known as: singular_name



181
182
183
# File 'lib/avo/resources/base.rb', line 181

def name
  name_from_translation_key(count: 1, default: class_name.underscore.humanize)
end

.name_from_translation_key(count:, default:) ⇒ Object

Get the name from the translation_key and fallback to default It can raise I18n::InvalidPluralizationData when using only resource_translation without pluralization keys like: one, two or other key Example:


en:

avo:
  resource_translations:
    product:
      save: "Save product"


199
200
201
202
203
# File 'lib/avo/resources/base.rb', line 199

def name_from_translation_key(count:, default:)
  t(translation_key, count:, default:).humanize
rescue I18n::InvalidPluralizationData
  default
end


209
210
211
# File 'lib/avo/resources/base.rb', line 209

def navigation_label
  plural_name.humanize
end

.plural_nameObject



186
187
188
# File 'lib/avo/resources/base.rb', line 186

def plural_name
  name_from_translation_key(count: 2, default: name.pluralize)
end

.query_scopeObject

This resolves the scope when doing “where” queries (not find queries)

It’s used to apply the authorization feature.



106
107
108
109
110
111
# File 'lib/avo/resources/base.rb', line 106

def query_scope
  authorization.apply_policy Avo::ExecutionContext.new(
    target: index_query,
    query: model_class
  ).handle
end

.route_keyObject



169
170
171
# File 'lib/avo/resources/base.rb', line 169

def route_key
  class_name.underscore.pluralize
end

.scope(scope_class) ⇒ Object



99
100
101
# File 'lib/avo/resources/base.rb', line 99

def scope(scope_class)
  deprecated_dsl_api __method__, "scopes"
end

.search_queryObject



234
235
236
# File 'lib/avo/resources/base.rb', line 234

def search_query
  search.dig(:query)
end

.search_results_countObject



238
239
240
# File 'lib/avo/resources/base.rb', line 238

def search_results_count
  search.dig(:results_count)
end

.singular_route_keyObject



173
174
175
# File 'lib/avo/resources/base.rb', line 173

def singular_route_key
  route_key.singularize
end

.translation_keyObject



177
178
179
# File 'lib/avo/resources/base.rb', line 177

def translation_key
  @translation_key || "avo.resource_translations.#{class_name.underscore}"
end

.underscore_nameObject



205
206
207
# File 'lib/avo/resources/base.rb', line 205

def underscore_name
  name.demodulize.underscore
end

.valid_association_name(record, association_name) ⇒ Object



124
125
126
# File 'lib/avo/resources/base.rb', line 124

def valid_association_name(record, association_name)
  association_name if record.class.reflect_on_association(association_name).present?
end

.valid_attachment_name(record, association_name) ⇒ Object



128
129
130
# File 'lib/avo/resources/base.rb', line 128

def valid_attachment_name(record, association_name)
  association_name if record.class.reflect_on_attachment(association_name).present?
end

Instance Method Details

#attachment_fieldsObject



443
444
445
446
447
# File 'lib/avo/resources/base.rb', line 443

def attachment_fields
  get_field_definitions.select do |field|
    [Avo::Fields::FileField, Avo::Fields::FilesField].include? field.class
  end
end

#authorization(user: nil) ⇒ Object



488
489
490
491
# File 'lib/avo/resources/base.rb', line 488

def authorization(user: nil)
  current_user = user || Avo::Current.user
  Avo::Services::AuthorizationService.new(current_user, record || model_class, policy_class: authorization_policy)
end

#available_view_typesObject



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/avo/resources/base.rb', line 424

def available_view_types
  if self.class.view_types.present?
    return Array(
      Avo::ExecutionContext.new(
        target: self.class.view_types,
        resource: self,
        record: record
      ).handle
    )
  end

  view_types = [:table]

  view_types << :grid if self.class.grid_view.present?
  view_types << :map if map_view.present?

  view_types
end

#avatarObject



586
587
588
589
590
591
592
593
594
# File 'lib/avo/resources/base.rb', line 586

def avatar
  return avatar_field.to_image if avatar_field.respond_to? :to_image

  return avatar_field.value.variant(resize_to_limit: [480, 480]) if avatar_field.type == "file"

  avatar_field.value
rescue
  nil
end

#avatar_fieldObject



578
579
580
581
582
583
584
# File 'lib/avo/resources/base.rb', line 578

def avatar_field
  get_field_definitions.find do |field|
    field.as_avatar.present?
  end
rescue
  nil
end

#avatar_typeObject



596
597
598
599
600
# File 'lib/avo/resources/base.rb', line 596

def avatar_type
  avatar_field.as_avatar
rescue
  nil
end

#cache_hash(parent_record) ⇒ Object



514
515
516
517
518
519
520
521
522
# File 'lib/avo/resources/base.rb', line 514

def cache_hash(parent_record)
  result = [record, file_hash]

  if parent_record.present?
    result << parent_record
  end

  result
end

#current_userObject



22
23
24
# File 'lib/avo/resources/base.rb', line 22

def current_user
  Avo::Current.user
end

#custom_componentsObject



634
635
636
637
638
639
640
641
# File 'lib/avo/resources/base.rb', line 634

def custom_components
  @custom_components ||= Avo::ExecutionContext.new(
    target: components,
    resource: self,
    record: @record,
    view: @view
  ).handle.with_indifferent_access
end

#default_panel_nameObject



382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/avo/resources/base.rb', line 382

def default_panel_name
  return @params[:related_name].capitalize if @params.present? && @params[:related_name].present?

  case @view.to_sym
  when :show
    record_title
  when :edit
    record_title
  when :new
    t("avo.create_new_item", item: name.humanize(capitalize: false)).upcase_first
  end
end

#description_attributesObject



618
619
620
621
622
623
624
# File 'lib/avo/resources/base.rb', line 618

def description_attributes
  {
    view: view,
    resource: self,
    record: record
  }
end

#detect_fieldsObject



276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/avo/resources/base.rb', line 276

def detect_fields
  self.items_holder = Avo::Resources::Items::Holder.new(parent: self)

  # Used in testing to replace items
  if temporary_items.present?
    instance_eval(&temporary_items)
  else
    fetch_fields
  end

  self
end

#divider(**kwargs) ⇒ Object



323
324
325
# File 'lib/avo/resources/base.rb', line 323

def divider(**kwargs)
  entity_loader(:action).use({class: Divider, **kwargs}.compact)
end

#entity_loader(entity) ⇒ Object



626
627
628
# File 'lib/avo/resources/base.rb', line 626

def entity_loader(entity)
  instance_variable_get(:"@#{entity.to_s.pluralize}_loader")
end

#fetch_cardsObject



319
320
321
# File 'lib/avo/resources/base.rb', line 319

def fetch_cards
  cards
end

#fetch_fieldsObject



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/avo/resources/base.rb', line 300

def fetch_fields
  if view.preview?
    [:fields, :index_fields, :show_fields, :display_fields].each do |fields_method|
      send(fields_method) if respond_to?(fields_method)
    end

    return
  end

  possible_methods_for_view = VIEW_METHODS_MAPPING[view.to_sym]

  # Safe navigation operator is used because the view can be "destroy"
  possible_methods_for_view&.each do |method_for_view|
    return send(method_for_view) if respond_to?(method_for_view)
  end

  fields
end

#fetch_record_titleObject



409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/avo/resources/base.rb', line 409

def fetch_record_title
  return name if @record.nil?

  # Get the title from the record if title is not set, try to get the name, title or label, or fallback to the to_param
  return @record.try(:name) || @record.try(:title) || @record.try(:label) || @record.to_param if title.nil?

  # If the title is a symbol, get the value from the record else execute the block/string
  case title
  when Symbol
    @record.send title
  when Proc
    Avo::ExecutionContext.new(target: title, resource: self, record: @record).handle
  end
end

#fields_by_database_idObject

Map the received params to their actual fields



450
451
452
453
454
455
456
457
458
459
# File 'lib/avo/resources/base.rb', line 450

def fields_by_database_id
  get_field_definitions
    .reject do |field|
      field.computed
    end
    .map do |field|
      [field.database_id.to_s, field]
    end
    .to_h
end

#file_hashObject



493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'lib/avo/resources/base.rb', line 493

def file_hash
  content_to_be_hashed = ""

  resource_path = Rails.root.join("app", "avo", "resources", "#{file_name}.rb").to_s
  if File.file? resource_path
    content_to_be_hashed += File.read(resource_path)
  end

  # policy file hash
  policy_path = Rails.root.join("app", "policies", "#{file_name.gsub("_resource", "")}_policy.rb").to_s
  if File.file? policy_path
    content_to_be_hashed += File.read(policy_path)
  end

  Digest::MD5.hexdigest(content_to_be_hashed)
end

#file_nameObject



510
511
512
# File 'lib/avo/resources/base.rb', line 510

def file_name
  @file_name ||= self.class.underscore_name.tr(" ", "_")
end

#fill_record(record, permitted_params, extra_params: [], fields: nil) ⇒ Object



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/avo/resources/base.rb', line 461

def fill_record(record, permitted_params, extra_params: [], fields: nil)
  # Write the field values
  permitted_params.each do |key, value|
    field = if fields.present?
      fields.find { |f| f.id == key.to_sym }
    else
      fields_by_database_id[key]
    end

    next unless field.present?

    record = field.fill_field record, key, value, permitted_params
  end

  # Write the user configured extra params to the record
  if extra_params.present?
    # Pick only the extra params
    # params at this point are already permited, only need the keys to access them
    extra_attributes = permitted_params.slice(*flatten_keys(extra_params))

    # Let Rails fill in the rest of the params
    record.assign_attributes extra_attributes
  end

  record
end

#form_scopeObject



602
603
604
# File 'lib/avo/resources/base.rb', line 602

def form_scope
  model_class.base_class.to_s.underscore.downcase
end

#has_record_id?Boolean

Returns:

  • (Boolean)


606
607
608
# File 'lib/avo/resources/base.rb', line 606

def has_record_id?
  record.present? && record_id.present?
end

#hydrateObject



372
373
374
375
376
377
378
379
380
# File 'lib/avo/resources/base.rb', line 372

def hydrate(...)
  super

  if @record.present?
    hydrate_model_with_default_values if @view&.new?
  end

  self
end

#hydrate_model_with_default_valuesObject

We will not overwrite any attributes that come pre-filled in the record.



525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/avo/resources/base.rb', line 525

def hydrate_model_with_default_values
  default_values = get_fields
    .select do |field|
      !field.computed && !field.is_a?(Avo::Fields::HeadingField)
    end
    .map do |field|
      value = field.value

      if field.type == "belongs_to"

        reflection = @record.class.reflect_on_association(@params[:via_relation]) if @params[:via_relation].present?

        if field.polymorphic_as.present? && field.types.map(&:to_s).include?(@params[:via_relation_class])
          # set the value to the actual record
          via_resource = Avo.resource_manager.get_resource_by_model_class(@params[:via_relation_class])
          value = via_resource.find_record(@params[:via_record_id])
        elsif reflection.present? && reflection.foreign_key.present? && field.id.to_s == @params[:via_relation].to_s
          resource = Avo.resource_manager.get_resource_by_model_class params[:via_relation_class]
          record = resource.find_record @params[:via_record_id], params: params
          id_param = reflection.options[:primary_key] || :id

          value = record.send(id_param)
        end
      end

      [field, value]
    end
    .to_h
    .select do |_, value|
      value.present?
    end

  default_values.each do |field, value|
    field.assign_value record: @record, value: value
  end
end

#id_attributeObject



610
611
612
# File 'lib/avo/resources/base.rb', line 610

def id_attribute
  :id
end

#model_classObject

Returns the model class being used for this resource.

We use the class method as a fallback but we pass it the record too so it can support the STI use cases where we figure out the model class from that record.



399
400
401
402
403
# File 'lib/avo/resources/base.rb', line 399

def model_class
  record_class = @record&.class

  self.class.model_class record_class: record_class
end

#model_nameObject



562
563
564
# File 'lib/avo/resources/base.rb', line 562

def model_name
  model_class.model_name
end

#record_idObject



614
615
616
# File 'lib/avo/resources/base.rb', line 614

def record_id
  record.send(id_attribute)
end

#record_paramObject



630
631
632
# File 'lib/avo/resources/base.rb', line 630

def record_param
  @record_param ||= @record.persisted? ? @record.to_param : nil
end

#record_pathObject



570
571
572
# File 'lib/avo/resources/base.rb', line 570

def record_path
  resource_path(record: record, resource: self)
end

#record_titleObject



405
406
407
# File 'lib/avo/resources/base.rb', line 405

def record_title
  fetch_record_title.to_s
end

#records_pathObject



574
575
576
# File 'lib/avo/resources/base.rb', line 574

def records_path
  resources_path(resource: self)
end

#resolve_component(original_component) ⇒ Object



643
644
645
# File 'lib/avo/resources/base.rb', line 643

def resolve_component(original_component)
  custom_components.dig(original_component.to_s)&.to_s&.safe_constantize || original_component
end

#singular_model_keyObject



566
567
568
# File 'lib/avo/resources/base.rb', line 566

def singular_model_key
  model_class.model_name.singular
end