How can I dry business logic between third-party Ruby and client-side Javascript?

I have a model Widgetwith inheritance (I use Single-Table Inheritance, but it is equally valid for a class at the table). Some of the subclasses require a specific field; others do not.

class Widget < ActiveRecord
  ALL_WIDGET_TYPES = [FooWidget, BarWidget, BazWidget]
end

class FooWidget < Widget
  validates_presence_of :color
end

class BarWidget < Widget
  # no color field
end

class BazWidget < Widget
  validates_presence_of :color
end

I am creating a New Widget form ( app/views/widgets/new.html.erb) and would like to dynamically display / hide the box colorbased on <select>for widget_type.

<% form_for @widget do |f| %>
  <%= f.select :type, Widget::ALL_WIDGET_TYPES %>
  <div class='hiddenUnlessWidgetTypeIsFooOrBaz'>
    <%= f.label :color %>
    <%= f.text_field :color %>
  </div>
<% end %>

I can easily write some jQuery for watching events onChangeon widget_type, but that would mean putting some constant WidgetTypesThatRequireColorin my Javascript. It is easy enough to do this manually, but it will most likely disconnect from the model classes Widget.

Javascript , content_for(:js) yield :js . ?

+3
1

html, . .

<select ...>
    <option class="widget colored">FooWidget</option>
    <option class="widget uncolored">BarWidget</option>
    <option class="widget colored">BazWidget</option>
</select>

jQ, div .

+3

Source: https://habr.com/ru/post/1741811/


All Articles