instance method acts_like?

Ruby on Rails 7.0.10

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

acts_like?(duck)

Provides a way to check whether some class acts like some other class based on the existence of an appropriately-named marker method.

A class that provides the same interface as SomeClass may define a marker method named acts_like_some_class? to signal its compatibility to callers of acts_like?(:some_class).

For example, Active Support extends Date to define an acts_like_date? method, and extends Time to define acts_like_time?. As a result, developers can call x.acts_like?(:time) and x.acts_like?(:date) to test duck-type compatibility, and classes that are able to act like Time can also define an acts_like_time? method to interoperate.

Note that the marker method is only expected to exist. It isn’t called, so its body or return value are irrelevant.

Example: A class that provides the same interface as String

This class may define:

class Stringish
  def acts_like_string?
  end
end

Then client code can query for duck-type-safeness this way:

Stringish.new.acts_like?(:string) # => true

Parameters

duck req
Source
# File activesupport/lib/active_support/core_ext/object/acts_like.rb, line 33
  def acts_like?(duck)
    case duck
    when :time
      respond_to? :acts_like_time?
    when :date
      respond_to? :acts_like_date?
    when :string
      respond_to? :acts_like_string?
    else
      respond_to? :"acts_like_#{duck}?"
    end
  end

Defined in activesupport/lib/active_support/core_ext/object/acts_like.rb line 33 · View on GitHub · Improve this page · Find usages on GitHub

Defined in Object

Type at least 2 characters to search.

↑↓ navigate · open · esc close