Module: DataAttributes::Helper

Defined in:
lib/data_attributes/helper.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.data_attribute_value(value, options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/data_attributes/helper.rb', line 5

def self.data_attribute_value(value, options = {})
  if value.is_a?(String) || value.is_a?(Symbol)
    options[:prefix_strings] ? "string:#{value}" : value.to_s
  elsif value.is_a?(Numeric)
    value
  elsif value.nil?
    nil
  elsif value.is_a?(Time)
    value.to_i
  elsif value.is_a?(Date)
    value.strftime('%Y/%m/%d')
  elsif value.is_a?(TrueClass) || value.is_a?(FalseClass)
    options[:raw] ? value : value.to_s
  elsif value.is_a?(Array)
    value = value.map { |v| data_attribute_value(v, options.merge(raw: true)) }
    options[:raw] ? value : value.to_json
  elsif value.is_a?(Hash)
    value = value.each_with_object({}) { |(k, v), hash| hash[k.to_s.gsub(/^_+/, '').gsub(/\?$/, '').camelize(:lower)] = data_attribute_value(v, options.merge(raw: true)) }
    options[:raw] ? value : value.to_json
  elsif value.is_a?(DataAttributes::Model)
    data_attribute_value(value.data_attributes, options)
  else
    raise "Can't convert object of class #{value.class} in data attributes"
  end
end

Instance Method Details

#content_tag_for_single_record(tag_name, record, prefix, options, &block) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/data_attributes/helper.rb', line 31

def (tag_name, record, prefix, options, &block)
  options, prefix = prefix, nil if prefix.is_a?(Hash)
  options ||= {}
  options[:data] ||= {}
  options[:data] = options[:data].data_attributes if options[:data].is_a?(DataAttributes::Model)
  options[:data].reverse_merge!(record.data_attributes) if record.is_a?(DataAttributes::Model)
  options.reverse_merge!(class: record.class.model_name.singular.dasherize)
  if block.arity == 0
    (tag_name, capture(&block), options)
  else
    (tag_name, capture(record, &block), options)
  end
end

#data_attribute_value(value, options = {}) ⇒ Object



45
46
47
# File 'lib/data_attributes/helper.rb', line 45

def data_attribute_value(value, options = {})
  DataAttributes::Helper.data_attribute_value(value, options)
end

#tag_options(options, escape = true) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/data_attributes/helper.rb', line 49

def tag_options(options, escape = true)
  (options.delete(:data) || options.delete('data') || {}).each do |key, value|
    value = data_attribute_value(value)
    value = html_escape(value) if escape
    options["data-#{key.to_s.gsub(/^_+/, '').gsub(/\?$/, '').dasherize}"] = value
  end
  super
end