Module: DomFor::Model

Included in:
DomFor
Defined in:
lib/dom_for/model.rb

Overview

Name of classes Pages: index - users new - user new_user edit - user edit_user show - user show_user

ID name Pages: index - users new - new_user edit - user_1 show - user_1

Data-attributes Pages: index - data-action = index new - data-action = new edit - data-action = edit, data-object-id = 1 show - data-action = show, data-object-id = 1

Instance Method Summary collapse

Instance Method Details

#dom_for_model(klass, attrs = {}, &block) ⇒ String

Creates a div tag with the attributes for the model of ActiveRecord

Examples:

Without the block:

dom_for_model(User) #=> <div class="users" id="users" />

When there is a request:

dom_for_model(User) #=> <div class="users" data-action="show" id="users" />

For the new user:

dom_for_model(User) #=> <div class="user new_user" data-action="new" id="new_user" />

For the saved record (if exists @user):

dom_for_model(User) #=> <div class="user show_user" data-action="show" data-object-id="1" data-object="users" id="user_1" />

With the additional attributes:

dom_for_model(User, admin: true) #=> <div class="user show_user" data-action="show" data-admin="true" data-object-id="1" data-object="users" id="user_1" />

With the block:

dom_for_model(User, admin: true) do
  tag(:span)
end #=> <div class="user show_user" data-action="show" data-admin="true" data-object-id="1" data-object="users" id="user_1"><span /></div>

Parameters:

  • klass (Class)

    Model of ActiveRecord::Base

  • attrs (Hash) (defaults to: {})

    Additional attributes for the record

  • block (Proc)

    Block for a div tag

Returns:

  • (String)

    Sanitized HTML string



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/dom_for/model.rb', line 54

def dom_for_model(klass, attrs={}, &block)
  object_classes  = []
  class_name      = klass.to_s.underscore
  request_action  = request.path_parameters[:action]

  attrs.merge!(action: request_action) if request_action.present?

  object = instance_variable_get("@#{class_name}")

  object_id = if object
                if object.persisted?
                  attrs = attrs.merge(object_id: object.id, object: class_name.pluralize)
                end

                object_classes << dom_class(klass)
                object_classes << dom_class(klass, request_action) if request_action.present?

                dom_id(object)
              else
                object_classes << class_name.pluralize

                class_name.pluralize
              end

  if block_given?
    (:div, id: object_id, class: object_classes.join(' '), data: attrs, &block)
  else
    tag(:div, id: object_id, class: object_classes.join(' '), data: attrs)
  end

rescue
  (:div, &block)
end