Answer the question
In order to leave comments, you need to log in
Where to store static variables and constants for view in RoR?
Good afternoon everyone. I mainly work on the front-end (now more vue, but I'm also familiar with angular), I work with rails according to circumstances (the backend of many projects I work on is written on rails). I had a bit of a snag understanding some of the basic concepts that this framework is built on. And the question is more about the representation of data, i.e. more related to views and related logic.
Let's assume that the application has a menu that presents a set of links: events, archive, blog, account, language, entry_btn. Several buttons have conditional dependencies, for example: the language selection button depends on the currently selected language, the content of the entry_btn button and the presence of the account button depends on whether the user is logged in or not.
the simplest, most obvious and well working solution:
/ slim-lang
ul.navbar__menu
li = link_to 'Events', root_path, class: 'navbar__item'
/ ... other links
li
- if I18n.locale == :ru
link_to 'Eng', locale_path(:en), 'navbar__item'
- else
link_to 'Ru', locale_path(:ru), 'navbar__item'
- if signed_in?
li = link_to 'Аккаунт', edit_user_registration_path, class: 'navbar__item'
li = link_to 'Выход', destroy_user_session_path, class: 'navbar__item', method: :delete
- else
li = link_to 'Вход', new_user_session_path, class: 'navbar__item'
/ slim-lang
- links = [{ label: 'Events', path: root_path }, ... ]
- links.each do |link|
li = link_to link[:label], link[:path], class: 'navbar__item'
/ для верстки мне нужно было разбить список на 2 дива, так что передаваемые символы в метод нужны для поиска объектов
- @navbar.links(:root, :archive, :blog, :locale, :entry_group).each do |link|
li = link_to link[:label], link[:path], class: 'navbar__item', **link[:options]
class NavbarPresenter < BasePresenter
include Rails.application.routes.url_helpers
def links *args
methods = args.select { |method| self.respond_to? method, :include_private and available_links.include? method }
links = methods.map { |method| self.send method }
links.flatten(1)
end
private
def format_link label, path, **args
{ label: label, path: path, options: args }
end
def available_links
[:root, :archive, :blog, :locale, :entry_group]
end
def blog
format_link I18n.t('header.items.blog'), posts_path
end
# ...
# other links with different logic
end
@navbar = NavbarPresenter.new(view_context)
, but it is so available for all views, but I would like to make it available only inside the navbar (my navbar is partial)Answer the question
In order to leave comments, you need to log in
The links method has no place in the controller. Move the method to a separate helper or use the cells gem
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question