Class: ActiveElement::Components::Util::RecordPath

Inherits:
Object
  • Object
show all
Defined in:
lib/active_element/components/util/record_path.rb

Overview

Generates Rails paths from records, used to generate form actions and links for Rails RESTful routes.

Instance Method Summary collapse

Constructor Details

#initialize(record:, controller:, type: nil) ⇒ RecordPath

Returns a new instance of RecordPath.



8
9
10
11
12
# File 'lib/active_element/components/util/record_path.rb', line 8

def initialize(record:, controller:, type: nil)
  @record = record
  @controller = controller
  @type = type&.to_sym || controller.action_name&.to_sym
end

Instance Method Details



22
23
24
# File 'lib/active_element/components/util/record_path.rb', line 22

def link(**kwargs)
  controller.helpers.link_to(DefaultDisplayValue.new(object: record).value, path(**kwargs))
end

#modelObject



26
27
28
29
30
31
32
# File 'lib/active_element/components/util/record_path.rb', line 26

def model
  all_names.find do |name|
    controller.helpers.public_send(record_path_for(name), *path_arguments)
  rescue NoMethodError
    nil
  end&.classify&.constantize || default_model
end

#namespaceObject



34
35
36
37
38
39
40
41
42
43
# File 'lib/active_element/components/util/record_path.rb', line 34

def namespace
  # XXX: We guess the namespace from the current controller's module name. This will work
  # most of the time but will break if the current record's controller exists in a different
  # namespace to the current controller, e.g. `BackEndAdmin::UsersController` and
  # `FrontEndAdmin::ThemesController` - if `FrontEndAdmin::ThemesController` renders a
  # collection of `User` objects, the "show" path will be wrong:
  # `front_end_admin_user_path`. Maybe descend through the full controller class tree to
  # find a best match ?
  controller.class.name.deconstantize.underscore.to_sym
end

#path(**kwargs) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/active_element/components/util/record_path.rb', line 14

def path(**kwargs)
  record_path(**kwargs)
rescue NoMethodError
  ActiveElement.warning("Unable to map #{record.inspect} to a Rails route (#{@controller.class.name}##{@type}). Tried:\n" \
                        "#{all_record_paths.join("\n")}")
  nil
end