Class: Enumpath::Resolver::Property

Inherits:
Object
  • Object
show all
Defined in:
lib/enumpath/resolver/property.rb

Overview

A utility for resolving a string as a property (a public method that expects no arguments) of an object.

Which properties resolve is decided by a property resolver policy, set with the :property_resolver option of Enumpath.apply:

  • :safe (the default): read-only access only. See Property.safe?.
  • :readers: :safe, plus public methods written in Ruby (including those of installed gems) and ActiveModel-style attributes. See Property.reader?. This runs application and gem code and is not read-only.
  • :none: never call methods. Indexes, keys and Struct or Data members still resolve through Simple.
  • :all: call any public method that expects no arguments. This was the behavior of version 0.1 and lets a path run mutating or destructive methods such as clear, pop or destroy. Only use it with trusted paths.
  • a callable (anything that responds to call, such as a lambda): called as callable.call(object, name) with the property name as a String; the method is called only when it returns a truthy value. The callable has full control: none of the checks of the other policies are applied. It can call Property.safe? or Property.reader? to build on them.

The policy for the current Enumpath.apply call is kept in a fiber-local variable (Thread.current), so it reaches every operator without being passed through each one, and calls running in other threads or fibers do not see it. Outside of Enumpath.apply, and in a chained Enumpath::Results#apply that does not pass the option again, the default (:safe) applies.

Constant Summary collapse

POLICIES =

The policies accepted by the :property_resolver option, besides a callable

%i[safe readers none all].freeze
DEFAULT_POLICY =

The policy used when none is given

:safe
IDENTIFIER =

Property names :safe and :readers will consider: plain identifiers, optionally ending in ?. Names ending in ! or =, operators and constant-like names are never called.

/\A[a-z_][A-Za-z0-9_]*\??\z/.freeze
SAFE_METHODS =

Read-only methods :safe calls on SAFE_RECEIVERS. Each returns a new value and leaves the receiver unchanged in Ruby's own implementation. Mutating methods (clear, pop, shift, delete, freeze, any ! method) are deliberately absent.

%w[
  length size count empty? any? all? none? one?
  first last min max minmax sum
  keys values entries to_a to_h
  reverse compact sort uniq flatten
  to_s to_sym to_i to_f to_r to_c
  nil? zero? nonzero? positive? negative? even? odd? finite? infinite? integer?
  abs floor ceil round truncate next pred succ
  upcase downcase capitalize swapcase strip lstrip rstrip chomp chop bytesize
].freeze
SAFE_RECEIVERS =

The plain data classes on which :safe calls SAFE_METHODS. Other objects that define methods with the same names (an IO, an Enumerator, a database relation, a custom collection) could run arbitrary code or consume input. Range is left out because methods like sum and sort never return on an endless range.

([Array, Hash, String, Symbol, Numeric, NilClass, TrueClass, FalseClass, Struct] +
[Simple::DATA_CLASS].compact).freeze
CORE_OWNERS =

Modules whose implementation of a SAFE_METHODS name is trusted. A subclass of a SAFE_RECEIVERS class that overrides one of these methods is not trusted.

(SAFE_RECEIVERS + [Kernel, Comparable, Enumerable, Integer, Float, Rational, Complex]).freeze
CORE_CLASSES =

Instances of these classes are core objects: their instance variables never make a property resolvable, and :readers treats them exactly like :safe. Modules and classes are included because their instance variables are usually internal state (memoized values, configuration), not data.

(SAFE_RECEIVERS + [Range, Module, Proc, Method, UnboundMethod, IO, Enumerator, Thread]).freeze
READERS_DENYLIST =

Common persistence verbs :readers refuses to call even when the object's class defines them. This is a safety net for ActiveRecord-style models, not a guarantee: :readers still runs any other public method that expects no arguments.

%w[destroy delete save update reload touch delete_all destroy_all toggle].freeze
THREAD_KEY =

The Thread.current key that holds the policy for the current Enumpath.apply call

:enumpath_property_resolver

Class Method Summary collapse

Class Method Details

.current_policy ⇒ Symbol, #call

The policy for the current Enumpath.apply call in this thread or fiber

Returns:

  • (Symbol, #call) —

    the current policy, or DEFAULT_POLICY when none is set



90
91
92
# File 'lib/enumpath/resolver/property.rb', line 90

def current_policy
  Thread.current[THREAD_KEY] || DEFAULT_POLICY
end

.reader?(object, name) ⇒ true, false

Whether the :readers policy resolves a property of an object. Core objects (see CORE_CLASSES) are treated exactly like safe?. For any other object, either

  • the name is a plain identifier (see IDENTIFIER), not in READERS_DENYLIST, and the object publicly responds to it with a method that expects no arguments and is written in Ruby outside of Ruby itself (see ObjectInspector.application_method?), so computed readers like full_name work; or
  • the object has an ActiveModel-style attributes method (no arguments, written in Ruby outside of Ruby itself) that returns a Hash with the name as a String key, so attributes like email work even before their reader methods are defined; or
  • safe? allows it.

In short, :readers runs any public method that expects no arguments and is written in Ruby, except Ruby's built-in methods, methods in the Ruby standard library directory, and READERS_DENYLIST. Methods implemented in C (core classes, StringIO, C-extension gems) are never called; objects of C-extension classes need a callable policy or :all. Methods from installed gems are called, including default and bundled gems such as Logger and CSV, and ActiveModel or ActiveRecord: for example Logger#close would run.

So :readers is not read-only. Use it for data you trust or objects you built. For untrusted paths use :safe, or a callable that builds on safe? with a per-class allowlist.

Parameters:

  • object (Object) —

    the object to read from

  • name (String) —

    the property name

Returns:

  • (true, false)


167
168
169
170
171
# File 'lib/enumpath/resolver/property.rb', line 167

def reader?(object, name)
  !reader_access(object, name).nil?
rescue StandardError
  false
end

.resolve(property, object, policy = current_policy) ⇒ Object

Attempts to resolve a string as a property of an object, as the policy allows

Parameters:

  • property (String) —

    the name of the property to attempt to resolve

  • object (Object) —

    the object to resolve the property against

  • policy (Symbol, #call) (defaults to: current_policy) —

    the property resolver policy to apply; defaults to current_policy

Returns:

  • the resolved property value, or nil if it could not be resolved or the policy does not allow it



81
82
83
84
85
# File 'lib/enumpath/resolver/property.rb', line 81

def resolve(property, object, policy = current_policy)
  access(policy, object, property.to_s)&.call
rescue ArgumentError, NoMethodError, TypeError, RangeError
  nil
end

.safe?(object, name) ⇒ true, false

Whether the :safe policy resolves a property of an object. All of these must hold:

  • the name is a plain identifier (see IDENTIFIER);
  • the object publicly responds to it and the method has no required arguments;
  • and either
    • the name is in SAFE_METHODS, the object is one of SAFE_RECEIVERS, and the method is Ruby's own (owned by one of CORE_OWNERS, not overridden), in which case the method is called; or
    • the object is not one of CORE_CLASSES and has an instance variable of the same name (@name for name), as an attr_reader on a plain Ruby object does. In that case the instance variable is read directly and the method itself is never called, so a method that merely shares its name with an instance variable cannot run.

Struct and Data members are not handled here: they resolve as members through Simple.

A callable policy can build on this check to allow more methods while keeping the safe ones:

Examples:

Keep the safe defaults and allow specific methods per class

ALLOWED = { 'Invoice' => %w[total due_on], 'Customer' => %w[name email] }.freeze
policy = lambda do |object, name|
  Enumpath::Resolver::Property.safe?(object, name) || ALLOWED.fetch(object.class.name, []).include?(name)
end
Enumpath.apply('invoices.*.total', , property_resolver: policy)

Parameters:

  • object (Object) —

    the object to read from

  • name (String) —

    the property name

Returns:

  • (true, false)


138
139
140
141
142
# File 'lib/enumpath/resolver/property.rb', line 138

def safe?(object, name)
  !safe_access(object, name).nil?
rescue StandardError
  false
end