Sha256: d200343e5f3806f16c8d7b4b6a4c2b1d4162c1ef3ea355c06fbd10bdb80cf5ce

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

module FlashRailsMessages
  class Base
    include ActionView::Context
    include ActionView::Helpers::TagHelper

    attr_reader :options

    def initialize(options = {})
      @options = options
    end

    def render(flash)
      messages(flash).map do |message|
        alert_element(*message)
      end.join.html_safe
    end

    private

    def messages(flash)
      Hash[flash]
        .symbolize_keys
        .keep_if { |key, _| alert_type_classes.include?(key) }
    end

    def alert_element(type, message)
      return unless message.respond_to?(:html_safe)

      content_tag :div, alert_options(type) do
        content = ActiveSupport::SafeBuffer.new
        content += close_element if options.fetch(:dismissible, false)
        content += message.html_safe
        content
      end
    end

    def close_element
      content_tag :a, class: 'close', href: '#' do
        '×'.html_safe
      end
    end

    def alert_options(type)
      default_alert_options
        .merge(options.except(:dismissible))
        .merge(class: alert_classes(type))
    end

    def alert_classes(type)
      [
        default_alert_classes,
        alert_type_classes[type],
        custom_alert_classes,
        options[:class]
      ].compact.join(' ').strip
    end

    def default_alert_options
      {}
    end

    def default_alert_classes
      'alert'
    end

    def alert_type_classes
      {}
    end

    def custom_alert_classes; end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
flash_rails_messages-2.3.0 lib/flash_rails_messages/base.rb