Module: DataAttributes::Helper
- Defined in:
- lib/data_attributes/helper.rb
Class Method Summary collapse
Instance Method Summary collapse
- #content_tag_for_single_record(tag_name, record, prefix, options, &block) ⇒ Object
- #data_attribute_value(value, options = {}) ⇒ Object
- #tag_options(options, escape = true) ⇒ Object
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, = {}) if value.is_a?(String) || value.is_a?(Symbol) [: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) [:raw] ? value : value.to_s elsif value.is_a?(Array) value = value.map { |v| data_attribute_value(v, .merge(raw: true)) } [: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, .merge(raw: true)) } [:raw] ? value : value.to_json elsif value.is_a?(DataAttributes::Model) data_attribute_value(value.data_attributes, ) 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 content_tag_for_single_record(tag_name, record, prefix, , &block) , prefix = prefix, nil if prefix.is_a?(Hash) ||= {} [:data] ||= {} [:data] = [:data].data_attributes if [:data].is_a?(DataAttributes::Model) [:data].reverse_merge!(record.data_attributes) if record.is_a?(DataAttributes::Model) .reverse_merge!(class: record.class.model_name.singular.dasherize) if block.arity == 0 content_tag(tag_name, capture(&block), ) else content_tag(tag_name, capture(record, &block), ) end end |
#data_attribute_value(value, options = {}) ⇒ Object
45 46 47 |
# File 'lib/data_attributes/helper.rb', line 45 def data_attribute_value(value, = {}) DataAttributes::Helper.data_attribute_value(value, ) end |
#tag_options(options, escape = true) ⇒ Object
49 50 51 52 53 54 55 56 |
# File 'lib/data_attributes/helper.rb', line 49 def (, escape = true) (.delete(:data) || .delete('data') || {}).each do |key, value| value = data_attribute_value(value) value = html_escape(value) if escape ["data-#{key.to_s.gsub(/^_+/, '').gsub(/\?$/, '').dasherize}"] = value end super end |