Use Rails methods to get map location input IDs

We were manually generating the IDs in order to pass them as data
attributes in the HTML in a component where we don't have access to the
form which has the inputs.

However, these data attributes only make sense when there's a form
present, so we can pass the form as a parameter and use it to get the
IDs.

We can now define a map as editable when there's an associated form,
which makes sense IMHO.
This commit is contained in:
Javi Martín
2023-03-07 19:18:45 +01:00
parent 84fff2e9fb
commit b9518d64e1
9 changed files with 30 additions and 30 deletions

View File

@@ -1,12 +1,11 @@
class Shared::MapLocationComponent < ApplicationComponent
attr_reader :parent_class, :remove_marker_label, :investments_coordinates
delegate :map_location_input_id, to: :helpers
attr_reader :remove_marker_label, :investments_coordinates, :form
def initialize(map_location, parent_class, remove_marker_label: nil, investments_coordinates: nil)
def initialize(map_location, remove_marker_label: nil, investments_coordinates: nil, form: nil)
@map_location = map_location
@parent_class = parent_class
@remove_marker_label = remove_marker_label
@investments_coordinates = investments_coordinates
@form = form
end
def map_location
@@ -16,7 +15,7 @@ class Shared::MapLocationComponent < ApplicationComponent
private
def editable?
remove_marker_label.present?
form.present?
end
def latitude
@@ -53,12 +52,25 @@ class Shared::MapLocationComponent < ApplicationComponent
map_tiles_provider_attribution: Rails.application.secrets.map_tiles_provider_attribution,
marker_editable: editable?,
marker_remove_selector: "##{remove_marker_link_id}",
latitude_input_selector: "##{map_location_input_id(parent_class, "latitude")}",
longitude_input_selector: "##{map_location_input_id(parent_class, "longitude")}",
zoom_input_selector: "##{map_location_input_id(parent_class, "zoom")}",
marker_investments_coordinates: investments_coordinates,
marker_latitude: map_location.latitude.presence,
marker_longitude: map_location.longitude.presence
}
}.merge(input_selectors)
end
def input_selectors
if form
{
latitude_input_selector: "##{input_id(:latitude)}",
longitude_input_selector: "##{input_id(:longitude)}",
zoom_input_selector: "##{input_id(:zoom)}"
}
else
{}
end
end
def input_id(attribute)
form.hidden_field(attribute).match(/ id="([^"]+)"/)[1]
end
end