Module: CtTableFor::ApplicationHelper

Defined in:
app/helpers/ct_table_for/application_helper.rb

Instance Method Summary collapse

Instance Method Details

#button_for_custom_action(record, options, extras) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'app/helpers/ct_table_for/application_helper.rb', line 236

def button_for_custom_action record, options, extras
  parsed_extras = parse_extras(extras)
  # `icons` is a Boolean-String option to limit `icon` option
  label = if parsed_extras[:icons].to_s == "false"
    parsed_extras[:title].presence || ""
  else
    %Q{<i class="#{CtTableFor.config.table_for_icon_font_base_class} #{CtTableFor.config.table_for_icon_font_base_class}-#{parsed_extras[:icon]}"></i>}
  end
  ancestors_list = parsed_extras[:ancestors].presence || ""
  ancestors = ancestors_list.split(",").map do |ancestor|
    record.send(ancestor)
  end
  custom_action_class = %Q{#{CtTableFor.config.table_for_default_action_base_class} #{parsed_extras[:class]}}
  options= {
    class: custom_action_class,
    method: parsed_extras[:method],
    title: parsed_extras[:title]
  }
  options[:target]= parsed_extras[:target] if parsed_extras[:target].present?
  link_to(label.html_safe, polymorphic_path([parsed_extras[:link]&.to_sym, *ancestors, record]), options)
end

#class_for_action(action, options) ⇒ Object



232
233
234
# File 'app/helpers/ct_table_for/application_helper.rb', line 232

def class_for_action action, options
  %Q{#{CtTableFor.config.table_for_default_action_base_class} #{options.dig(:btn_class, action.to_sym) || CtTableFor.config.table_for_action_class[action.to_sym]}}
end

#get_css_classes(record, options = {}) ⇒ Object



272
273
274
275
276
# File 'app/helpers/ct_table_for/application_helper.rb', line 272

def get_css_classes(record, options = {})
  style = options[:style].try(:call, record) || ""
  tr_class = options[:tr_class] || ""
  "class='#{tr_class} #{style}'"
end

#label_for_action(action, icons = true) ⇒ Object



224
225
226
227
228
229
230
# File 'app/helpers/ct_table_for/application_helper.rb', line 224

def label_for_action action, icons = true
  label = I18n.t(action.to_sym, scope: [:table_for, :buttons]).capitalize
  if icons != false
    label = %Q{<i class="#{CtTableFor.config.table_for_icon_font_base_class} #{CtTableFor.config.table_for_icon_font_base_class}-#{CtTableFor.config.table_for_action_icons[action.to_sym]}"></i>}
  end
  label
end

#parse_extras(extras) ⇒ Object



268
269
270
# File 'app/helpers/ct_table_for/application_helper.rb', line 268

def parse_extras(extras)
  Hash[extras.collect { |extra| [extra.split(":").first, extra.split(":").last] } ].with_indifferent_access
end


94
95
96
97
98
99
100
101
102
# File 'app/helpers/ct_table_for/application_helper.rb', line 94

def row_data_link(record, options)
  return unless options[:clickable]
  if options[:clickable].kind_of?(Array)
    nested_resources = (options[:clickable] || []) + [record]
  else
    nested_resources = record
  end
  "data-link =" << polymorphic_url(nested_resources)
end

#table_for(model, collection, options: {}) ⇒ Object

RWD Table use as: table_for Model, @collection, options: {} options:

 style: "lambda {|model| method(model)"  // String: adds a method for css class
 actions: {
   buttons: %w(show, edit)},          // Hash: with array of buttons for actions
   premodel: [:bo, :admin],           // Array: of symbols for nested namespaces/models
   icons: true                        // Boolean: if true show actions as icons
 }
 attributes: %(name:sortable email),  // Array: of model attibutes to show in table
                                      // with extra parameter `:` add cell options (sort, image size)
                                      // if the attribute is a relation pass the attribute to show
                                      // if the attribute has an association will show a number with the count
 id: "my-id",                         // String: adds custom id to <table> element
 class: "my-custom-css",              // String: add custom class to <table> element
 tr_class: "my-custom-css"            // String: add custom class to <tr> element
 btn_class: {                         // Hash: add custom class to action buttons
   show: "my-custom-css",
   edit: "my-custom-css"
 }
clickable: true || Array              // Boolean or Array of nested resources for polymorphic_url

}



30
31
32
33
34
35
36
37
38
39
# File 'app/helpers/ct_table_for/application_helper.rb', line 30

def table_for model, collection, options: {}
  custom_id = options[:id].present? ? %Q{id="#{options[:id]}"} : ""
  html = %Q{<div class="table-for-wrapper #{CtTableFor.config.table_for_wrapper_default_class}">}
    html << %Q{<table #{custom_id} class="table-for #{CtTableFor.config.table_for_default_class} #{options[:class]} #{("table-clickable") if options[:clickable]}">}
      html << table_for_header(model, has_actions: options[:actions].present?, options: options)
      html << table_for_content(model, collection, options: options)
    html << %Q{</table>}
  html << %Q{</div>}
  html.html_safe
end

#table_for_actions(record, options: {}) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'app/helpers/ct_table_for/application_helper.rb', line 188

def table_for_actions(record, options: {} )
  return "" if options[:actions].blank?
  html = ""
  html << %Q{<td data-link-enabled="false" class="#{CtTableFor.config.table_for_td_default_prefix_class}-actions">}
    html << %Q{<div class="btn-group btn-group-sm" role="group" aria-label="#{I18n.t(:actions, scope: [:table_for]).capitalize}">}
    nesting = (options[:actions][:premodel] || []) + [record]
    buttons = options[:actions][:buttons].map{ |b| b.split("|")}
    buttons.each do |action, *extras|
      if defined?(CanCanCan) && cannot?(action.to_sym, record)
        html << ""
      else
        case action.to_sym
        when :show
          html << link_to(label_for_action(action, options[:actions][:icons]).html_safe, polymorphic_path(nesting), class: class_for_action(action, options))
        when :edit
          url_helper = options.dig(:actions, :urls, :edit) || lambda{|obj| edit_polymorphic_path(nesting)}
          html << link_to(label_for_action(action, options[:actions][:icons]).html_safe, url_helper.(nesting), class: class_for_action(action, options))
        when :destroy
          url_helper = options.dig(:actions, :urls, :destroy) || lambda{|obj| polymorphic_path(nesting)}
          html << link_to(label_for_action(action, options[:actions][:icons]).html_safe, url_helper.(nesting),
                          method: :delete, class: class_for_action(action, options), data: { confirm: I18n.t('table_for.messages.are_you_sure').capitalize })
        when :custom
          html << button_for_custom_action(record, options, extras)
        else
          # TODO:
          # nesting_custom = nesting + btn_options[0]
          # label = icon CtTableFor.config.table_for_action_icons[:custom] if options[:actions][:icons] != false and defined?(FontAwesome)
          # html << link_to(label, polymorphic_path(nesting_custom), class: "btn btn-default btn-sm")
        end
      end
    end
    html << %Q{</div>}
  html << %Q{</td>}
  html.html_safe
end

#table_for_attributes(model, options) ⇒ Object



41
42
43
# File 'app/helpers/ct_table_for/application_helper.rb', line 41

def table_for_attributes model, options
  options[:attributes] || model.attribute_names
end

#table_for_cell(model, record, attribute, cell_options: {}) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'app/helpers/ct_table_for/application_helper.rb', line 104

def table_for_cell model, record, attribute, cell_options: {}
  html = ""
  value = if record.respond_to?(attribute.to_sym)
            record.send(attribute.to_sym)
          elsif self.respond_to?(attribute.to_sym)
            self.send(attribute.to_sym, record)
          else
            nil
          end

  html << %Q{<td data-title="#{model.human_attribute_name("#{attribute}")}" class="#{CtTableFor.config.table_for_td_default_prefix_class}-#{attribute}">}
    case value
    when NilClass
      html << %Q{<i class="fa fa-minus text-muted"></i>}
    when TrueClass, FalseClass
      html << %Q{<i class="fa #{value ? "fa-check text-success" : "fa-times text-danger"}"></i>}
    when Numeric
      if cell_options.include? "currency"
        html << number_to_currency(value)
      elsif cell_options.include? "percentage"
        html << number_to_percentage(value, precision: CtTableFor.config.table_for_numeric_percentage_precision)
      else
        html << %Q{#{number_with_delimiter(value)}}
      end
    when ActiveSupport::TimeWithZone
      # TODO: value.in_time_zone
      html << %Q{<code>#{value.strftime("%d/%m/%Y %H:%M:%S")}</code>}
    when Date
      html << %Q{#{value.strftime("%d/%m/%Y")}}
    when Time
      # TODO: value.in_time_zone
      html << %Q{<code>#{value.strftime("%H:%M:%S")}</code>}
    when ActiveRecord::Base
      if cell_options.present?
       html << %Q{#{value.send cell_options[0]}}
      else
        html << %{#{(value.try(:title) || value.try(:name))}}
      end
    when ActiveRecord::Associations::CollectionProxy
      html << %Q{#{value.count}}
    else
      if defined?(ActiveStorage) && value.is_a?(ActiveStorage::Attached::One)
        html << table_for_cell_for_image( record, attribute, cell_options: cell_options )
      elsif uri?(value)
        html << link_to(value, value)
      elsif defined?(Paperclip) and value.is_a?(Paperclip::Attachment)
        html << table_for_cell_for_image( record, attribute, cell_options: cell_options )
      else
        if cell_options.include? "l"
          html << table_for_cell_for_locale(model, attribute, value)
        elsif cell_options.include? "no_truncate"
          html << value.to_s
        else
          html << value.to_s.truncate(
            CtTableFor.config.table_for_truncate_length,
            separator: CtTableFor.config.table_for_truncate_separator,
            omission: CtTableFor.config.table_for_truncate_omission
          )
        end
      end
    end
  html << %Q{</td>}
  html.html_safe
end

#table_for_cell_for_image(record, attribute, cell_options: {}) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'app/helpers/ct_table_for/application_helper.rb', line 169

def table_for_cell_for_image record, attribute, cell_options: {}
  html = ""
  size = cell_options.select{ |opt| ["thumb", "original", "small", "medium"].include? opt }.first || "thumb"
  value = record.send(attribute)
  return html unless value.present?

  if value.is_a?(ActiveStorage::Attached::One)
    html << image_tag(value, class: CtTableFor.config.table_for_cell_for_image_image_class, style: "max-height: 100px;")
  else
    html << image_tag(value.url(size), class: CtTableFor.config.table_for_cell_for_image_image_class, style: "max-height: 100px;")
  end
  html.html_safe
end

#table_for_cell_for_locale(model, attribute, value, cell_options: {}) ⇒ Object



183
184
185
# File 'app/helpers/ct_table_for/application_helper.rb', line 183

def table_for_cell_for_locale model, attribute, value, cell_options: {}
  html = model.human_attribute_name("#{attribute.underscore}.#{value.underscore}")
end

#table_for_content(model, collection, options: {}) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'app/helpers/ct_table_for/application_helper.rb', line 69

def table_for_content model, collection, options: {}
  html = ""
  html << %Q{<tbody>}
    if collection.present?
      collection.each do |record|
        css_classes = get_css_classes(record, options)
        html << %Q{<tr data-colection-id="#{record.try(:id)}" #{css_classes} #{row_data_link(record, options)}>}
          table_for_attributes(model, options).each do |attribute|
            attribute, *params = attribute.split(":")
            html << table_for_cell( model, record, attribute, cell_options: params )
          end
          html << table_for_actions( record, options: options) if options[:actions].present?
        html << %Q{</tr>}
      end
    else
      html << %Q{<tr>}
        html << %Q{<td colspan=#{options[:attributes].size + 1}>}
          html << I18n.t("table_for.messages.no_records")
        html << %Q{</td>}
      html << %Q{</tr>}
    end
  html << %Q{</tbody>}
  html.html_safe
end

#table_for_header(model, has_actions: false, options: {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'app/helpers/ct_table_for/application_helper.rb', line 45

def table_for_header model, has_actions: false, options: {}
  html = ""
  html << %Q{<thead>}
    html << %Q{<tr>}
      table_for_attributes(model, options).each do |attribute|
        html << %Q{<th>}
          attribute, *params = attribute.split(":")
          html << if defined?(Ransack) and params.include? "sortable"
            if params.length > 1 && (params & ['l', 'currency']).empty?
              sort_link(@q, "#{attribute}_#{params.first}", I18n.t("#{attribute.to_s.underscore}_#{params.first}", scope: [:activerecord, :attributes, model.to_s.underscore]).capitalize )
            else
              sort_link(@q, attribute, I18n.t("#{attribute}", scope: [:activerecord, :attributes, model.to_s.underscore]).capitalize )
            end
          else
            model.human_attribute_name("#{attribute}")
          end
        html << %Q{</th>}
      end
      html << %Q{<th class="actions">#{I18n.t(:actions, scope: [:table_for]).capitalize}</th>} if has_actions
    html << %Q{</tr>}
  html << %Q{</thead>}
  html.html_safe
end

#uri?(string) ⇒ Boolean

Returns:

  • (Boolean)


258
259
260
261
262
263
264
265
266
# File 'app/helpers/ct_table_for/application_helper.rb', line 258

def uri?(string)
  # http://ruby-doc.org/stdlib-2.4.0/libdoc/uri/rdoc/URI.html
  uri = URI.parse(string)
  %w( http https ).include?(uri.scheme)
rescue URI::BadURIError
  false
rescue URI::InvalidURIError
  false
end