Sha256: e2dfbca0ac093baf85eaaf83b8db4c65646515d7b4b968f7b121d957255145c9

Contents?: true

Size: 1.12 KB

Versions: 5

Compression:

Stored size: 1.12 KB

Contents

# frozen_string_literal: true

require "stimulus_reflex/utils/attribute_builder"

class StimulusReflex::Dataset < OpenStruct
  include StimulusReflex::AttributeBuilder

  attr_accessor :attrs, :data_attrs

  def initialize(data = {})
    datasets = data["dataset"] || {}
    regular_dataset = datasets["dataset"] || {}
    @attrs = build_data_attrs(regular_dataset, datasets["datasetAll"] || {})
    @data_attrs = @attrs.transform_keys { |key| key.delete_prefix "data-" }

    super build_underscored(@data_attrs)
  end

  def signed
    @signed ||= ->(accessor) { GlobalID::Locator.locate_signed(self[accessor]) }
  end

  def unsigned
    @unsigned ||= ->(accessor) { GlobalID::Locator.locate(self[accessor]) }
  end

  def boolean
    @boolean ||= ->(accessor) { cast_boolean(self[accessor]) || self[accessor].blank? }
  end

  def numeric
    @numeric ||= ->(accessor) { Float(self[accessor]) }
  end

  private

  def cast_boolean(value)
    ((value == "") ? nil : !false_values.include?(value)) unless value.nil?
  end

  def false_values
    @false_values ||= [false, 0, "0", "f", "F", "false", "FALSE", "off", "OFF"].to_set
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
stimulus_reflex-3.5.0.rc4 lib/stimulus_reflex/dataset.rb
stimulus_reflex-3.5.0.rc3 lib/stimulus_reflex/dataset.rb
stimulus_reflex-3.5.0.rc2 lib/stimulus_reflex/dataset.rb
stimulus_reflex-3.5.0.rc1 lib/stimulus_reflex/dataset.rb
stimulus_reflex-3.5.0.pre10 lib/stimulus_reflex/dataset.rb