Sha256: 7233bc80653cc046bf6a4c2f8531225955853ee035306e497ef005cb3f10b921

Contents?: true

Size: 1.42 KB

Versions: 4

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

require 'active_support/core_ext/array/wrap'

class ActiveSet
  class Instruction
    attr_reader :keypath, :value

    def initialize(keypath, value)
      # `keypath` can be an Array (e.g. [:parent, :child, :grandchild])
      # or a String (e.g. 'parent.child.grandchild')
      @keypath = Array.wrap(keypath).map(&:to_s).flat_map { |x| x.split('.') }
      @value = value
    end

    def attribute
      attribute = @keypath.last
      return attribute.sub(operator_regex, '') if attribute&.match operator_regex

      attribute
    end

    def operator(default: '==')
      attribute = @keypath.last
      return attribute[operator_regex, 1] if attribute&.match operator_regex

      default
    end

    def associations_array
      return [] unless @keypath.any?

      @keypath.slice(0, @keypath.length - 1)
    end

    def associations_hash
      return {} unless @keypath.any?

      associations_array.reverse.reduce({}) do |hash, association|
        { association => hash }
      end
    end

    def value_for(item:)
      resource_for(item: item).public_send(attribute)
    rescue
      nil
    end

    def resource_for(item:)
      associations_array.reduce(item) do |resource, association|
        return nil unless resource.respond_to? association

        resource.public_send(association)
      end
    rescue
      nil
    end

    private

    def operator_regex
      /\((.*?)\)/
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
activeset-0.6.3 lib/active_set/instruction.rb
activeset-0.6.2 lib/active_set/instruction.rb
activeset-0.6.1 lib/active_set/instruction.rb
activeset-0.6.0 lib/active_set/instruction.rb