1
0
Fork 0
mirror of https://github.com/heartcombo/simple_form.git synced 2022-11-09 12:19:26 -05:00
heartcombo--simple_form/test/components/custom_components_test.rb
Felipe Renan b12ad4abc4 Add API to register custom components
With this API, Simple Form will be possible to add custom components.
Methods defined in a component will be exposed to be used in the
wrapper as Simple::Components

Examples

  # The application needs to tell where the components will be.
  Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f }

  # Create a custom component in the path specified above.
  # lib/components/input_group_component.rb
  module InpoutGroupComponent
    def preprend
      ...
    end

    def append
      ...
    end
  end

  SimpleForm.setup do |config|
    # Create a wrapper using the custom component.
    config.wrappers :input_group, tag: :div, error_class: :error do |b|
      b.use :label
      b.optional :prepend
      b.use :input
      b.use :append
    end
  end

  # Using the custom component in the form.
  <%= simple_form_for @blog, wrapper: input_group do |f| %>
    <%= f.input :title, prepend: true %>
  <% end %>
2018-03-15 21:27:45 -03:00

62 lines
1.8 KiB
Ruby

# frozen_string_literal: true
require 'test_helper'
# Module that represents a custom component.
module Numbers
def number(wrapper_options = nil)
@number ||= options[:number].to_s.html_safe
end
end
# Module that represents a custom component.
module InputGroup
def prepend(wrapper_options = nil)
span_tag = content_tag(:span, options[:prepend], class: 'input-group-text')
template.content_tag(:div, span_tag, class: 'input-group-prepend')
end
def append(wrapper_options = nil)
span_tag = content_tag(:span, options[:append], class: 'input-group-text')
template.content_tag(:div, span_tag, class: 'input-group-append')
end
end
class CustomComponentsTest < ActionView::TestCase
test 'includes the custom components' do
SimpleForm.include_component Numbers
custom_wrapper = SimpleForm.build tag: :div, class: "custom_wrapper" do |b|
b.use :number, wrap_with: { tag: 'div', class: 'number' }
end
with_form_for @user, :name, number: 1, wrapper: custom_wrapper
assert_select 'div.number', text: '1'
end
test 'includes custom components and use it as optional in the wrapper' do
SimpleForm.include_component InputGroup
custom_wrapper = SimpleForm.build tag: :div, class: 'custom_wrapper' do |b|
b.use :label
b.optional :prepend
b.use :input
b.use :append
end
with_form_for @user, :name, prepend: true, wrapper: custom_wrapper
assert_select 'div.input-group-prepend > span.input-group-text'
assert_select 'div.input-group-append > span.input-group-text'
end
test 'raises a TypeError when the component is not a Module' do
component = 'MyComponent'
exception = assert_raises TypeError do
SimpleForm.include_component(component)
end
assert_equal exception.message, "SimpleForm.include_component expects a module but got: String"
end
end