Module: ApplicationHelper

Defined in:
app/helpers/application_helper.rb

Overview

##### BEGIN LICENSE BLOCK ##### Ekylibre - Simple agricultural ERP Copyright (C) 2009 Brice Texier, Thibaud Merigon

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with this program. If not, see <www.gnu.org/licenses/>.

##### END LICENSE BLOCK #####

Defined Under Namespace

Classes: AttributesList

Instance Method Summary collapse

Instance Method Details

#are_you_sure_you_want_to(action_expr, options = {}) ⇒ Object


720
721
722
723
724
725
# File 'app/helpers/application_helper.rb', line 720

def are_you_sure_you_want_to(action_expr, options = {})
  options[:default] ||= []
  options[:default] = [options[:default]] unless options[:default].is_a?(Array)
  options[:default] << "are_you_sure_you_want_to_#{action_expr}".tl(options)
  "are_you_sure_you_want_to.#{action_expr}".tl(options)
end

#attribute_item(object, attribute, options = {}) ⇒ Object


276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'app/helpers/application_helper.rb', line 276

def attribute_item(object, attribute, options = {})
  value_class = 'value'
  if object.is_a? String
    label = object
    value = attribute
    value = value.to_s unless [String, TrueClass, FalseClass].include? value.class
  else
    #     label = object.class.human_attribute_name(attribute.to_s)
    value = object.send(attribute)
    model = object.class
    model_name = model.name.underscore
    default = ["activerecord.attributes.#{model_name}.#{attribute}_id".to_sym]
    default << "activerecord.attributes.#{model_name}.#{attribute.to_s[0..-7]}".to_sym if attribute.to_s =~ /_label$/
    default << "attributes.#{attribute}".to_sym
    default << "attributes.#{attribute}_id".to_sym
    label = "activerecord.attributes.#{model_name}.#{attribute}".t(default: default)
    if value.is_a? ActiveRecord::Base
      record = value
      value = record.send(options[:label] || [:label, :name, :code, :number, :inspect].detect { |x| record.respond_to?(x) })
      options[:url] = { action: :show } if options[:url].is_a? TrueClass
      if options[:url].is_a? Hash
        options[:url][:id] ||= record.id
        #  raise [model_name.pluralize, record, record.class.name.underscore.pluralize].inspect
        options[:url][:controller] ||= record.class.name.underscore.pluralize
      end
    elsif value.is_a? Nomen::Item
      value = value.human_name
    else
      options[:url] = { action: :show } if options[:url].is_a? TrueClass
      if options[:url].is_a? Hash
        options[:url][:controller] ||= object.class.name.underscore.pluralize
        options[:url][:id] ||= object.id
      end
    end
    value_class << ' code' if attribute.to_s == 'code'
  end
  if [TrueClass, FalseClass].include? value.class
    value = (:div, '', class: "checkbox-#{value}")
  elsif value.respond_to?(:text)
    value = value.send(:text)
  elsif attribute.to_s =~ /(^|_)currency$/
    value = Nomen::Currency[value].human_name
  elsif options[:currency] && value.is_a?(Numeric)
    value = ::I18n.localize(value, currency: (options[:currency].is_a?(TrueClass) ? object.send(:currency) : options[:currency].is_a?(Symbol) ? object.send(options[:currency]) : options[:currency]))
    value = link_to(value.to_s, options[:url]) if options[:url]
  elsif value.respond_to?(:strftime) || value.respond_to?(:l) || value.is_a?(Numeric)
    value = value.l
    value = link_to(value.to_s, options[:url]) if options[:url]
  elsif options[:duration]
    duration = value
    duration *= 60 if options[:duration] == :minutes
    duration *= 3600 if options[:duration] == :hours
    hours = (duration / 3600).floor.to_i
    minutes = (duration / 60 - 60 * hours).floor.to_i
    seconds = (duration - 60 * minutes - 3600 * hours).round.to_i
    value = :duration_in_hours_and_minutes.tl(hours: hours, minutes: minutes, seconds: seconds)
    value = link_to(value.to_s, options[:url]) if options[:url]
  elsif value.is_a? String
    classes = []
    classes << 'code' if attribute.to_s == 'code'
    classes << value.class.name.underscore
    value = link_to(value.to_s, options[:url]) if options[:url]
    value = (:div, value.html_safe, class: classes.join(' '))
  end
  [label, value]
end

#attributes_list(*args, &block) ⇒ Object


343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'app/helpers/application_helper.rb', line 343

def attributes_list(*args, &block)
  options = args.extract_options!
  record = args.shift || resource
  columns = options[:columns] || 3
  attribute_list = AttributesList.new(record)
  if block_given?
    unless block.arity == 1
      raise ArgumentError, 'One parameter needed for attribute_list block'
    end
    yield attribute_list
  end
  if resource.customizable? && !options[:custom_fields].is_a?(FalseClass) &&
     !attribute_list.items.detect { |item| item[0] == :custom_fields }
    attribute_list.custom_fields
  end
  unless options[:stamps].is_a?(FalseClass)
    attribute_list.attribute :creator, label: :full_name
    attribute_list.attribute :created_at
    attribute_list.attribute :updater, label: :full_name
    attribute_list.attribute :updated_at
    # attribute_list.attribute :lock_version
  end
  code = ''
  items = attribute_list.items # .delete_if { |x| x[0] == :custom_fields }
  if items.any?
    for item in items
      label, value = if item[0] == :custom
                       attribute_item(*item[1])
                     elsif item[0] == :attribute
                       attribute_item(record, *item[1])
                     end
      if !value.blank? || (item[2].is_a?(Hash) && item[2][:show] == :always)
        code << (:dl, (:dt, label) + (:dd, value))
      end
    end
    code = (:div, code.html_safe, class: 'attributes-list')
  end
  code.html_safe
end

#authorized?(url_options = {}) ⇒ Boolean

Helper which check authorization of an action


27
28
29
# File 'app/helpers/application_helper.rb', line 27

def authorized?(url_options = {})
  controller.authorized?(url_options)
end

#available_languages(native_language = true) ⇒ Object


240
241
242
243
244
# File 'app/helpers/application_helper.rb', line 240

def available_languages(native_language = true)
  I18n.available_locales.map do |l|
    [native_language ? I18n.t('i18n.name', locale: l) : Nomen::Language.find(l).human_name, l]
  end.sort { |a, b| a.second <=> b.second }
end

#back_urlObject


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

def back_url
  :back
end

#backend_fields_for(object, *args, &block) ⇒ Object


828
829
830
831
# File 'app/helpers/application_helper.rb', line 828

def backend_fields_for(object, *args, &block)
  options = args.extract_options!
  simple_fields_for(object, *(args << options.merge(builder: Backend::FormBuilder)), &block)
end

#backend_form_for(object, *args, &block) ⇒ Object


817
818
819
820
821
822
823
824
825
826
# File 'app/helpers/application_helper.rb', line 817

def backend_form_for(object, *args, &block)
  options = args.extract_options!

  if options.fetch(:data, {}).key?(:defaults) && options[:data][:defaults].is_a?(Hash)
    options[:data][:defaults].each do |k, v|
      object.send("#{k}=", v) if object.has_attribute?(k)
    end
  end
  simple_form_for([:backend, object], *(args << options.merge(builder: Backend::FormBuilder)), &block)
end

#button_group(options = {}, &block) ⇒ Object


412
413
414
415
# File 'app/helpers/application_helper.rb', line 412

def button_group(options = {}, &block)
  options[:class] = options[:class].to_s + ' btn-group'
  (:div, options, &block)
end

#choices_yes_noObject


61
62
63
# File 'app/helpers/application_helper.rb', line 61

def choices_yes_no
  [[::I18n.translate('general.y'), true], [I18n.t('general.n'), false]]
end

#condition_label(condition) ⇒ Object


878
879
880
881
882
883
884
885
886
# File 'app/helpers/application_helper.rb', line 878

def condition_label(condition)
  if condition =~ /^generic/
    klass = condition.split(/\-/)[1].pluralize.classify.constantize
    attribute = condition.split(/\-/)[2]
    return tl('conditions.filter_on_attribute_of_class', attribute: klass.human_attribute_name(attribute), class: klass.model_name.human)
  else
    return tl("conditions.#{condition}")
  end
end

#countriesObject


228
229
230
# File 'app/helpers/application_helper.rb', line 228

def countries
  nomenclature_as_options(:countries)
end

#currenciesObject


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

def currencies
  nomenclature_as_options(:currencies)
end

#doctype_tagObject


513
514
515
# File 'app/helpers/application_helper.rb', line 513

def doctype_tag
  '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'.html_safe
end

Yields:

  • (l)

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# File 'app/helpers/application_helper.rb', line 480

def dropdown_button(*args)
  options = args.extract_options!
  l = Ekylibre::Support::Lister.new(:link_to)
  yield l
  minimum = 0
  if args[0].nil?
    return nil unless l.any?
    minimum = 1
    args = l.first.args
  end

  if l.size > minimum
    return (:div, class: 'btn-group') do # btn-group btn-group-dropdown  #{args[2][:class]}
      html = ''.html_safe
      html << tool_to(*args)
      html << dropdown_toggle_button
      html << (:ul, class: 'dropdown-menu', role: 'menu') do
        l.collect do |link|
          (:li, send(link.name, *link.args, &link.block))
        end.join.html_safe
      end
      html
    end
  else
    return tool_to(*args)
  end
end

426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'app/helpers/application_helper.rb', line 426

def dropdown_menu(items)
  (:ul, class: 'dropdown-menu') do
    items.map do |item|
      if item.name == :item
        args = item.args
        options = args.extract_options!
        item_options = {}
        item_options[:class] = options.delete(:as) if options.key?(:as)
        (:li, link_to(*args, options, &item.block), item_options)
      elsif item.name == :separator
        (:li, '', class: 'separator')
      else
        raise 'Cannot handle that type of menu item: ' + item.name.inspect
      end
    end.join.html_safe
  end
end

Yields:

  • (menu)

444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'app/helpers/application_helper.rb', line 444

def dropdown_menu_button(name, options = {})
  menu = Ekylibre::Support::Lister.new(:item, :separator)
  yield menu
  return nil unless menu.any?
  menu_size = menu.size
  default_item = menu.detect_and_extract! do |item|
    item.args[2].is_a?(Hash) && item.args[2][:by_default]
  end
  raise 'Need a name or a default item' unless name || default_item
  if name.is_a?(Symbol)
    options[:icon] ||= name unless options[:icon].is_a?(FalseClass)
    name = options[:label] || name.ta(default: ["labels.#{name}".to_sym])
  end
  item_options = default_item.args.third if default_item
  item_options ||= {}
  item_options[:tool] = options[:icon] if options.key?(:icon)
  (:div, class: 'btn-group' + (options[:class] ? ' ' + options[:class].to_s : '')) do
    if default_item
      html = tool_to(default_item.args.first, default_item.args.second,
                     item_options, &default_item.block)
      if menu_size > 1
        html << dropdown_toggle_button + dropdown_menu(menu.items)
      end
      html
    elsif menu.list.size == 1 && menu.first.type == :item
      default_item = menu.first
      tool_to(name, default_item.args.second,
              (default_item.args.third || {}).merge(item_options),
              &default_item.block)
    else
      dropdown_toggle_button(name, icon: options[:icon]) +
        dropdown_menu(menu.list)
    end
  end
end

417
418
419
420
421
422
423
424
# File 'app/helpers/application_helper.rb', line 417

def dropdown_toggle_button(name = nil, options = {})
  class_attribute = 'btn btn-default dropdown-toggle'
  class_attribute << ' sr-only' if name.blank?
  class_attribute << ' icn btn-' + options[:icon].to_s if options[:icon]
  (:button, name, class: class_attribute,
                             data: { toggle: 'dropdown' },
                             aria: { haspopup: 'true', expanded: 'false' })
end

#enumerize_as_options(model, attribute, *args) ⇒ Object

Returns a selection from names list


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

def enumerize_as_options(model, attribute, *args)
  options = args.extract_options!
  enum = model.to_s.camelize.constantize.send(attribute)
  items = args.shift || enum.values
  items.collect do |name|
    [name.l, name]
  end.sort { |a, b| a.first <=> b.first }
end

#error_messages(object) ⇒ Object


783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
# File 'app/helpers/application_helper.rb', line 783

def error_messages(object)
  object = instance_variable_get("@#{object}") unless object.respond_to?(:errors)
  return unless object.respond_to?(:errors)
  if (count = object.errors.size).zero?
    ''
  else
    I18n.with_options scope: [:errors, :template] do |locale|
      header_message = locale.t :header, count: count, model: object.class.model_name.human
      introduction = locale.t(:body)
      messages = object.errors.full_messages.map do |msg|
        (:li, msg)
      end.join.html_safe
      message = ''
      message << (:h3, header_message) unless header_message.blank?
      message << (:p, introduction) unless introduction.blank?
      message << (:ul, messages)

      html = ''
      html << (:div, '', class: :icon)
      html << (:div, message.html_safe, class: :message)
      html << (:div, '', class: :end)
      return (:div, html.html_safe, class: 'flash error')
    end
  end
end

#field(label, input, options = {}, &block) ⇒ Object

Wraps a label and its input in a standard wrapper


834
835
836
837
838
839
840
841
842
# File 'app/helpers/application_helper.rb', line 834

def field(label, input, options = {}, &block)
  options[:label] ||= {}
  options[:controls] ||= {}

  (:div,
              (:label, label, class: "control-label #{options[:label].key?(:class) ? options[:label][:class] : ''}") +
              (:div, (block_given? ? capture(&block) : input.is_a?(Hash) ? field_tag(input) : input), class: "controls #{options[:controls].key?(:class) ? options[:controls][:class] : ''}"),
              class: 'control-group')
end

#field_set(*args, &block) ⇒ Object


844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
# File 'app/helpers/application_helper.rb', line 844

def field_set(*args, &block)
  options = args.extract_options!
  options[:fields_class] ||= 'fieldset-fields'
  name = args.shift || 'general-informations'.to_sym
  buttons = [options[:buttons] || []].flatten
  buttons << link_to('', '#', :class => 'toggle', 'data-toggle' => 'fields')
  class_names = 'fieldset ' + name.to_s + (options[:class] ? ' ' + options[:class].to_s : '')
  class_names << (options[:collapsed] ? ' collapsed' : ' not-collapsed')
  name_sym = name.to_s.tr('-', '_').to_sym
  wrap((:div,
                   (:div,
                               link_to((:i) + h(name.is_a?(Symbol) ? name_sym.tl(default: ["form.legends.#{name_sym}".to_sym, "attributes.#{name_sym}".to_sym, name_sym.to_s.humanize]) : name.to_s), '#', :class => 'title', 'data-toggle' => 'fields') +
                               (:span, buttons.join.html_safe, class: :buttons),
                               class: 'fieldset-legend') +
                   (:div, capture(&block), class: options[:fields_class]), class: class_names, id: name), options[:in])

  # "#{name}-fieldset"
end

#form_actions(&block) ⇒ Object


809
810
811
# File 'app/helpers/application_helper.rb', line 809

def form_actions(&block)
  (:div, capture(&block), class: 'form-actions')
end

#form_fields(&block) ⇒ Object


813
814
815
# File 'app/helpers/application_helper.rb', line 813

def form_fields(&block)
  (:div, capture(&block), class: 'form-fields')
end

#heading_tagObject


648
649
650
# File 'app/helpers/application_helper.rb', line 648

def heading_tag
  (:h1, main_title, id: :title)
end

#heading_toolbar_tagObject

Build the heading toolbar


758
759
760
# File 'app/helpers/application_helper.rb', line 758

def heading_toolbar_tag
  toolbar_tag(:heading)
end

#human_age(born_at, options = {}) ⇒ Object


90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'app/helpers/application_helper.rb', line 90

def human_age(born_at, options = {})
  options[:default] ||= '&ndash;'.html_safe
  return options[:default] if born_at.nil?
  at = options[:at] || Time.zone.now
  sign = ''
  if born_at > at
    sign = '-'
    at, born_at = born_at, at
  end
  vals = []
  remaining_at = born_at + 0.seconds
  %w(year month day hour minute second).each do |magnitude|
    count = 0
    while remaining_at + 1.send(magnitude) < at
      remaining_at += 1.send(magnitude)
      count += 1
    end
    if count > 0 && (!options[:display] || vals.size < options[:display])
      vals << "x_#{magnitude.pluralize}".tl(count: count)
    end
  end
  sign + vals.to_sentence
end

#human_duration(seconds, options = {}) ⇒ Object


136
137
138
139
140
141
142
143
144
145
# File 'app/helpers/application_helper.rb', line 136

def human_duration(seconds, options = {})
  return options[:default] || '&ndash;'.html_safe if seconds.nil?
  vals = []
  vals << (seconds / 1.hour).floor
  seconds -= 1.hour * (seconds / 1.hour).floor
  vals << (seconds / 1.minute).floor.to_s.rjust(2, '0')
  seconds -= 1.minute * (seconds / 1.minute).floor
  # vals << seconds.round.to_s.rjust(2, "0")
  vals.join(':')
end

#human_interval(seconds, options = {}) ⇒ Object


114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'app/helpers/application_helper.rb', line 114

def human_interval(seconds, options = {})
  return options[:default] || '&ndash;'.html_safe if seconds.nil?
  vals = []
  if (seconds.to_f / 1.year).floor > 0.0 && (!options[:display] || vals.size < options[:display])
    vals << :x_years.tl(count: (seconds / 1.year).floor)
    seconds -= 1.year * (seconds / 1.year).floor
  end
  if (seconds.to_f / 1.month).floor > 0.0 && (!options[:display] || vals.size < options[:display])
    vals << :x_months.tl(count: (seconds / 1.month).floor)
    seconds -= 1.month * (seconds / 1.month).floor
  end
  if (seconds.to_f / 1.day).floor > 0.0 && (!options[:display] || vals.size < options[:display])
    vals << :x_days.tl(count: (seconds / 1.day).floor)
    seconds -= 1.day * (seconds / 1.day).floor
  end
  if (seconds.to_f / 1.hour).floor > 0.0 && (!options[:display] || vals.size < options[:display])
    vals << :x_hours.tl(count: (seconds / 1.hour).floor)
    seconds -= 1.hour * (seconds / 1.hour).floor
  end
  vals.to_sentence
end

#icon_tags(options = {}) ⇒ Object


560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# File 'app/helpers/application_helper.rb', line 560

def icon_tags(options = {})
  # Favicon
  html = tag(:link, rel: 'icon', type: 'image/png', href: image_path('icon/favicon.png'), 'data-turbolinks-track' => true)
  html << "\n".html_safe + tag(:link, rel: 'shortcut icon', href: image_path('icon/favicon.ico'), 'data-turbolinks-track' => true)
  # Apple touch icon
  icon_sizes = { iphone: '57x57', ipad: '72x72', 'iphone-retina' => '114x114', 'ipad-retina' => '144x144' }
  unless options[:app].is_a?(FalseClass)
    for name, sizes in icon_sizes
      html << "\n".html_safe + tag(:link, rel: 'apple-touch-icon', sizes: sizes, href: image_path("icon/#{name}.png"), 'data-turbolinks-track' => true)
    end
  end
  if options[:precomposed]
    for name, sizes in icon_sizes
      html << "\n".html_safe + tag(:link, rel: 'apple-touch-icon-precomposed', sizes: sizes, href: image_path("icon/precomposed-#{name}.png"), 'data-turbolinks-track' => true)
    end
  end
  html
end

#languagesObject


236
237
238
# File 'app/helpers/application_helper.rb', line 236

def languages
  nomenclature_as_options(:languages)
end

#last_page(menu) ⇒ Object


508
509
510
511
# File 'app/helpers/application_helper.rb', line 508

def last_page(menu)
  # session[:last_page][menu.to_s]||
  url_for(controller: :dashboards, action: menu)
end

#legals_sentenceObject

LEGALS_ITEMS = [h(“Ekylibre ” + Ekylibre.version), h(“Ruby on Rails ” + Rails.version), h(“Ruby ”+ RUBY_VERSION.to_s)].join(“ &ndash; ”.html_safe).freeze


54
55
56
57
58
59
# File 'app/helpers/application_helper.rb', line 54

def legals_sentence
  # "Ekylibre " << Ekylibre.version << " - Ruby on Rails " << Rails.version << " - Ruby #{RUBY_VERSION} - " << ActiveRecord::Base.connection.adapter_name << " - " << ActiveRecord::Migrator.current_version.to_s
  nbsp = '&nbsp;'.html_safe # ,  h("Ruby on Rails") + nbsp + Rails.version, ("HTML" + nbsp + "5").html_sa, h("CSS 3")
  [h('Ekylibre') + nbsp + Ekylibre.version].join(' &ndash; ').html_safe # ,  h("Ruby") + nbsp + RUBY_VERSION.to_s
  # return content_tag(:span, content_tag(:i, '') + nbsp + h("Ekylibre"), class: "brand") + nbsp + h(Ekylibre.version)
end

218
219
220
221
222
223
224
225
226
# File 'app/helpers/application_helper.rb', line 218

def li_link_to(*args)
  options = args[1] || {}
  # if authorized?({:controller => controller_name, :action => action_name}.merge(options))
  if authorized?({ controller: controller_path, action: :index }.merge(options))
    (:li, link_to(*args).html_safe)
  else
    ''
  end
end

Re-writing of link_to helper


180
181
182
183
184
185
186
187
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
# File 'app/helpers/application_helper.rb', line 180

def link_to(*args, &block)
  if block_given?
    options      = args.first || {}
    html_options = args.second
    link_to(capture(&block), options, html_options)
  else
    name         = args[0]
    options      = args[1] || {}
    html_options = args[2] || {}

    if options.is_a? Hash
      return (html_options[:remove] ? '' : (:a, name, class: html_options[:class].to_s + ' forbidden', disabled: true)) unless authorized?(options)
    end

    html_options = convert_options_to_data_attributes(options, html_options)
    begin
      url = url_for(options)
    rescue ActionController::UrlGenerationError => uge
      # Trying to fail gracefully in production
      raise uge unless Rails.env.production?
      ExceptionNotifier::Notifier.exception_notification(request.env, uge).deliver
      request.env['exception_notifier.delivered'] = true
      return (:a, name, class: html_options[:class].to_s + ' invalid invalid-route', disabled: true)
    end

    if html_options
      html_options = html_options.stringify_keys
      href = html_options['href']
      tag_options = tag_options(html_options)
    else
      tag_options = nil
    end

    href_attr = 'href="' + url + '"' unless href
    "<a #{href_attr}#{tag_options}>".html_safe + (name || url) + '</a>'.html_safe
  end
end

271
272
273
274
# File 'app/helpers/application_helper.rb', line 271

def link_to_back(options = {})
  options[:label] ||= :back
  link_to(options[:label].is_a?(String) ? options[:label] : options[:label].tl, back_url)
end

175
176
177
# File 'app/helpers/application_helper.rb', line 175

def link_to_remove_nested_association(name, f, options = {})
  link_to_remove_association((:i) + h("labels.remove_#{name}".t(default: :destroy.ta)), f, options.deep_merge(data: { no_turbolink: true }, class: 'nested-remove'))
end

#locale_selector_tagObject

def locale_selector

# , :selected => ::I18n.locale)
locales = ::I18n.available_locales.sort{|a,b| a.to_s <=> b.to_s}
locale = nil # ::I18n.locale
if params[:locale].to_s.match(/^[a-z][a-z][a-z]$/)
  locale = params[:locale].to_sym if locales.include? params[:locale].to_sym
end
locale ||= ::I18n.locale||::I18n.default_locale
options = locales.collect do |l|
  (:option, ::I18n.translate("i18n.name", :locale => l), {:value => l, :dir => ::I18n.translate("i18n.dir", :locale => l)}.merge(locale == l ? {:selected => true} : {}))
end.join.html_safe
select_tag("locale", options, "data-redirect" => url_for())

end


161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'app/helpers/application_helper.rb', line 161

def locale_selector_tag
  locales = ::I18n.available_locales.sort { |a, b| a.to_s <=> b.to_s }
  # locales = ::I18n.valid_locales.sort{|a,b| a.to_s <=> b.to_s}
  locale = nil # ::I18n.locale
  if params[:locale].to_s =~ /^[a-z][a-z][a-z]$/
    locale = params[:locale].to_sym if locales.include? params[:locale].to_sym
  end
  locale ||= ::I18n.locale || ::I18n.default_locale
  options = locales.collect do |l|
    (:option, ::I18n.translate('i18n.name', locale: l), { :value => l, :dir => ::I18n.translate('i18n.dir', locale: l), :selected => false, 'data-redirect' => url_for(locale: l) }.merge(locale == l ? { selected: true } : {}))
  end.join.html_safe
  select_tag('locale', options, 'data-use-redirect' => 'true')
end

#main_attachmentsObject


612
613
614
615
616
617
618
619
# File 'app/helpers/application_helper.rb', line 612

def main_attachments
  # Modal to display file
  modal(:file_preview, data: { attachment_thumblink_target: true }) do
     :div, nil, class: 'modal-body'
  end

  render(partial: 'attachments')
end

#main_informations(options = {}, &block) ⇒ Object


603
604
605
606
607
608
609
610
# File 'app/helpers/application_helper.rb', line 603

def main_informations(options = {}, &block)
  html = (:div, class: 'panel', id: 'main-informations') do
    partial = (:div, class: 'panel-body', &block)
    partial += (:div, main_attachments, class: 'panel-footer') if options[:attachment]
    partial
  end
  html
end

#main_title(value = nil) ⇒ Object


621
622
623
624
625
626
627
628
629
630
631
# File 'app/helpers/application_helper.rb', line 621

def main_title(value = nil)
  if value || block_given?
    if block_given?
      content_for(:main_title, &block)
    else
      content_for(:main_title, value)
    end
  else
    return (content_for?(:main_title) ? content_for(:main_title) : controller.human_action_name)
  end
end

#main_toolbar(options = {}, &block) ⇒ Object

Create the main toolbar with the same API as toolbar


778
779
780
781
# File 'app/helpers/application_helper.rb', line 778

def main_toolbar(options = {}, &block)
  content_for(:main_toolbar, toolbar(options.merge(wrap: false), &block))
  nil
end

#main_toolbar_tagObject

Build the main toolbar


773
774
775
# File 'app/helpers/application_helper.rb', line 773

def main_toolbar_tag
  toolbar_tag(:main)
end

TOOLBAR

Raises:

  • (ArgumentError)

709
710
711
712
713
714
715
716
717
718
# File 'app/helpers/application_helper.rb', line 709

def menu_to(name, url, options = {})
  raise ArgumentError, "##{__method__} cannot use blocks" if block_given?
  icon = (options.key?(:menu) ? options.delete(:menu) : url.is_a?(Hash) ? url[:action] : nil)
  sprite = options.delete(:sprite) || 'icons-16'
  options[:class] = (options[:class].blank? ? 'mn' : options[:class] + ' mn')
  options[:class] += ' ' + icon.to_s if icon
  link_to(url, options) do
    (icon ? (:span, '', class: 'icon') + (:span, name, class: 'text') : (:span, name, class: 'text'))
  end
end

#meta_toolbar_tagObject

Build the meta toolbar


763
764
765
# File 'app/helpers/application_helper.rb', line 763

def meta_toolbar_tag
  toolbar_tag(:meta)
end

Define a simple frame for modals


889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
# File 'app/helpers/application_helper.rb', line 889

def modal(*args, &block)
  options = args.extract_options!
  options[:aria] ||= {}
  options[:aria][:hidden] ||= 'true'
  options[:aria][:labelledby] ||= options.delete(:labelledby) if options[:labelledby]
  if options[:class].is_a? Array
    options[:class] << 'modal'
    options[:class] << 'fade'
  elsif options[:class].nil?
    options[:class] = 'modal fade'
  else
    options[:class] = options[:class].to_s + ' modal fade'
  end
  if (id = args.shift) && !options[:id]
    if id.is_a?(Symbol)
      options[:id] = id.to_s.dasherize
      options[:title] ||= id.tl
    else
      options[:id] = id
    end
  end
  title = options.delete(:title) || options.delete(:heading)
  options[:aria][:labelledby] ||= options[:id].underscore.camelcase(:lower)
  options[:tabindex] ||= '-1'
  options[:role] ||= 'dialog'
  header_options = options.slice(:close_button, :close_html).merge(title_id: options[:aria][:labelledby])
  content_for(:popover) do
    (:div, options) do
      (:div, class: 'modal-dialog') do
        (:div, class: 'modal-content') do
          if title
            modal_header(title, header_options) + capture(&block)
          else
            capture(&block)
          end
        end
      end
    end
  end
end

930
931
932
933
934
935
936
937
938
939
940
941
# File 'app/helpers/application_helper.rb', line 930

def modal_header(title, options = {})
  title_id = options[:title_id] || title.parameterize.underscore.camelcase(:lower)
  (:div, class: 'modal-header') do
    if options[:close_button].is_a? FalseClass
      (:h4, title, class: 'modal-title', id: title_id)
    else
      button_tag({ class: 'close', aria: { label: :close.tl }, data: { dismiss: 'modal' }, type: 'button' }.deep_merge(options[:close_html] || {})) do
        (:span, '&times;'.html_safe, aria: { hidden: 'true' })
      end + (:h4, title, class: 'modal-title', id: title_id)
    end
  end
end

#nomenclature_as_options(nomenclature_name, *args) ⇒ Object

Returns a selection from names list


247
248
249
250
251
252
253
254
255
# File 'app/helpers/application_helper.rb', line 247

def nomenclature_as_options(nomenclature_name, *args)
  options = args.extract_options!
  nomenclature = Nomen[nomenclature_name]
  items = args.shift || nomenclature.all
  items.collect do |name|
    item = nomenclature.find(name)
    [item.human_name, item.name]
  end.sort { |a, b| a.first <=> b.first }
end

#notification_tag(mode, messages = nil) ⇒ Object


668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'app/helpers/application_helper.rb', line 668

def notification_tag(mode, messages = nil)
  unless messages
    if flash[:notifications].is_a?(Hash) && flash[:notifications][mode.to_s].is_a?(Array)
      messages = flash[:notifications][mode.to_s]
    end
  end
  messages = [messages] if messages.is_a?(String)
  code = ''.html_safe
  return code unless messages
  messages.each do |message|
    code << "<div class='flash #{mode}' data-alert=\"true\"><a href=\"#\" class=\"close\">&times;</a><div class='icon'></div><div class='message'><h3>#{mode.t(scope: 'notifications.levels')}</h3><p>#{h(message).gsub(/\n/, '<br/>')}</p></div></div>".html_safe
  end
  code
end

#notifications_tagObject


683
684
685
686
687
688
# File 'app/helpers/application_helper.rb', line 683

def notifications_tag
  notification_tag(:error) <<
    notification_tag(:warning) <<
    notification_tag(:success) <<
    notification_tag(:information)
end

#number_to_accountancy(value, currency = nil) ⇒ Object


80
81
82
83
# File 'app/helpers/application_helper.rb', line 80

def number_to_accountancy(value, currency = nil)
  number = value.to_f
  (number.zero? ? '' : number.l(currency: currency || Preference[:currency]))
end

#number_to_management(value) ⇒ Object


85
86
87
88
# File 'app/helpers/application_helper.rb', line 85

def number_to_management(value)
  number = value.to_f
  number.l
end

#product_stocks_options(product) ⇒ Object


871
872
873
874
875
876
# File 'app/helpers/application_helper.rb', line 871

def product_stocks_options(product)
  options = []
  options += product.stocks.collect { |x| [x.label, x.id] }
  options += Building.of_product(product).collect { |x| [x.name, -x.id] }
  options
end

#radio_check_box(object_name, method, _options = {}, checked_value = '1', unchecked_value = '0') ⇒ Object


72
73
74
75
76
77
78
# File 'app/helpers/application_helper.rb', line 72

def radio_check_box(object_name, method, _options = {}, checked_value = '1', unchecked_value = '0')
  # raise StandardError.new eval("@#{object_name}.#{method}").inspect
  radio_button_tag(object_name, method, TrueClass, id: "#{object_name}_#{method}_#{checked_value}") << ' ' <<
    (:label, ::I18n.translate('general.y'), for: "#{object_name}_#{method}_#{checked_value}") << ' ' <<
    radio_button_tag(object_name, method, FalseClass, id: "#{object_name}_#{method}_#{unchecked_value}") << ' ' <<
    (:label, ::I18n.translate('general.n'), for: "#{object_name}_#{method}_#{unchecked_value}")
end

#radio_yes_no(name, value = nil) ⇒ Object


65
66
67
68
69
70
# File 'app/helpers/application_helper.rb', line 65

def radio_yes_no(name, value = nil)
  radio_button_tag(name, 1, value.to_s == '1', id => "#{name}_1") <<
    (:label, ::I18n.translate('general.y'), for: "#{name}_1") <<
    radio_button_tag(name, 0, value.to_s == '0', id => "#{name}_0") <<
    (:label, ::I18n.translate('general.n'), for: "#{name}_0")
end

#relative_distance_in_words(time) ⇒ Object


943
944
945
946
947
948
949
950
# File 'app/helpers/application_helper.rb', line 943

def relative_distance_in_words(time)
  now = Time.zone.now
  if time > now
    'datetime.relative_distance_in_words.in_sometime'.t(distance: time_ago_in_words(time))
  else
    'datetime.relative_distance_in_words.sometime_ago'.t(distance: time_ago_in_words(time))
  end
end

#search_results(search, _options = {}, &block) ⇒ Object


517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'app/helpers/application_helper.rb', line 517

def search_results(search, _options = {}, &block)
  (:div, class: :search) do
    # Show results
    html = ''.html_safe
    html << (:ul, class: :results) do
      counter = 'a'
      search[:records].collect do |result|
        id = 'result-' + counter
        counter.succ!
        (:li, class: 'result', id: id) do
          (block.arity == 2 ? capture(result, id, &block) : capture(result, &block)).html_safe
        end
      end.join.html_safe
    end if search[:records]

    # Pagination
    html << (:span, class: :pagination) do
      padding = 9
      gap = 4
      page_min = params[:page].to_i - padding
      page_min = 1 if page_min < gap
      page_max = params[:page].to_i + padding
      page_max = search[:last_page] if page_max > search[:last_page]

      pagination = ''
      if page_min > 1
        pagination << link_to((:i) + tl(:beginning), { q: params[:q], page: 1 }, class: :beginning)
        pagination << (:span, '&hellip;'.html_safe) if page_min >= gap
      end
      for p in page_min..page_max
        attrs = {}
        attrs[:class] = 'active' if p == params[:page]
        pagination << link_to(p.to_s, { q: params[:q], page: p }, attrs)
      end
      pagination << (:span, '&hellip;'.html_safe) if page_max < search[:last_page]
      pagination.html_safe
    end if search[:last_page] && search[:last_page] > 1

    # Return HTML
    html
  end
end

#selector(object_name, association, choices, options = {}, html_options = {}) ⇒ Object


40
41
42
43
44
45
46
47
48
49
50
# File 'app/helpers/application_helper.rb', line 40

def selector(object_name, association, choices, options = {}, html_options = {})
  object = options[:object] || instance_variable_get("@#{object_name}")
  model = object.class
  unless reflection = object.class.reflect_on_association(association)
    raise ArgumentError, "Unknown reflection for #{model.name}: #{association.inspect}"
  end
  if reflection.macro != :belongs_to
    raise ArgumentError, "Reflection #{reflection.name} must be a belongs_to"
  end
  text_field(object_name, reflection.foreign_key, html_options.merge('data-selector' => url_for(choices)))
end

#selector_tag(name, choices = nil, options = {}, html_options = {}) ⇒ Object


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

def selector_tag(name, choices = nil, options = {}, html_options = {})
  choices ||= :unroll
  choices = { action: choices } if choices.is_a?(Symbol)
  html_options[:data] ||= {}
  html_options[:data][:selector] = url_for(choices)
  html_options[:data][:selector_new_item] = url_for(options[:new]) if options[:new]
  text_field_tag(name, options[:value], html_options)
end

#subheading(i18n_key, options = {}) ⇒ Object

Raises:

  • (StandardError)

652
653
654
655
656
657
658
659
# File 'app/helpers/application_helper.rb', line 652

def subheading(i18n_key, options = {})
  raise StandardError, 'A subheading has already been given.' if content_for?(:subheading)
  if options[:here]
    return subheading_tag(tl(i18n_key, options))
  else
    content_for(:subheading, tl(i18n_key, options))
  end
end

#subheading_tag(title = nil) ⇒ Object


661
662
663
664
665
666
# File 'app/helpers/application_helper.rb', line 661

def subheading_tag(title = nil)
  if content_for?(:subheading) || title
    return (:h2, title || content_for(:subheading), id: :subtitle)
  end
  nil
end

#svg(_options = {}, &block) ⇒ Object


408
409
410
# File 'app/helpers/application_helper.rb', line 408

def svg(_options = {}, &block)
  (:svg, capture(&block))
end

#table_of(array, html_options = {}, &block) ⇒ Object


690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'app/helpers/application_helper.rb', line 690

def table_of(array, html_options = {}, &block)
  coln = html_options.delete(:columns) || 3
  html = ''
  item = ''
  size = 0
  for item in array
    item << (:td, capture(item, &block))
    size += 1
    next unless size >= coln
    html << (:tr, item).html_safe
    item = ''
    size = 0
  end
  html << (:tr, item).html_safe unless item.blank?
  (:table, html, html_options).html_safe
end

#theme_button(name, theme = nil) ⇒ Object


590
591
592
# File 'app/helpers/application_helper.rb', line 590

def theme_button(name, theme = nil)
  image_path(theme_path("buttons/#{name}.png", theme))
end

Permits to use themes for Ekylibre

stylesheet_link_tag 'application', 'list', 'list-colors'
stylesheet_link_tag 'print', :media => 'print'

582
583
584
585
586
587
588
# File 'app/helpers/application_helper.rb', line 582

def theme_link_tag(theme = nil)
  theme ||= current_theme
  return nil unless theme
  html = ''
  html << stylesheet_link_tag(theme_path('all.css', theme), media: :all, 'data-turbolinks-track' => true)
  html.html_safe
end

#theme_path(name, theme = nil) ⇒ Object


594
595
596
597
# File 'app/helpers/application_helper.rb', line 594

def theme_path(name, theme = nil)
  theme ||= current_theme
  "themes/#{theme}/#{name}"
end

#title_tagObject


633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'app/helpers/application_helper.rb', line 633

def title_tag
  r = [] # reverse_menus
  title = if current_user
            code = request.url.split(/(\:\/\/|\.)/).third
            if r.empty?
              :page_title_special.tl(company_code: code, action: main_title)
            else
              :page_title.tl(company_code: code, action: main_title, menu: "menus.#{r[0]}".tl)
            end
          else
            :page_title_by_default.tl(action: main_title)
          end
  (:title, title)
end

#tool_to(name, url, options = {}) ⇒ Object

def tool(code = nil, &block)

raise ArgumentError.new("Arguments XOR block code are accepted, but not together.") if (code and block_given?) or (code.blank? and !block_given?)
code = capture(&block) if block_given?
content_for(:main_toolbar_default, code)
return true

end

Raises:

  • (ArgumentError)

734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
# File 'app/helpers/application_helper.rb', line 734

def tool_to(name, url, options = {})
  raise ArgumentError, "##{__method__} cannot use blocks" if block_given?
  icon = options.delete(:tool)
  icon ||= url[:action] if url.is_a?(Hash) && !icon.is_a?(FalseClass)
  options[:class] = (options[:class].blank? ? 'btn btn-default' : options[:class].to_s + ' btn btn-default')
  options[:class] << ' icn btn-' + icon.to_s if icon
  if url.is_a?(Hash)
    if url.key?(:redirect)
      url.delete(:redirect) if url[:redirect].nil?
    else
      url[:redirect] = request.fullpath
    end
  end
  link_to(name, url, options)
end

#toolbar_tag(name) ⇒ Object


750
751
752
753
754
755
# File 'app/helpers/application_helper.rb', line 750

def toolbar_tag(name)
  toolbar = "#{name}_toolbar".to_sym
  if content_for?(toolbar)
    return (:div, content_for(toolbar), class: "#{name.to_s.parameterize}-toolbar toolbar")
  end
end

#view_toolbar_tagObject

Build the view toolbar


768
769
770
# File 'app/helpers/application_helper.rb', line 768

def view_toolbar_tag
  toolbar_tag(:view)
end

#viewport_tagObject


599
600
601
# File 'app/helpers/application_helper.rb', line 599

def viewport_tag
  tag(:meta, name: 'viewport', content: 'width=device-width, initial-scale=1.0, maximum-scale=1.0')
end

#wrap(html, *levels) ⇒ Object


863
864
865
866
867
868
869
# File 'app/helpers/application_helper.rb', line 863

def wrap(html, *levels)
  if levels.any?
    level = levels.shift
    return wrap((:div, html, class: level), *levels)
  end
  html
end